无法访问函数内部的全局变量

这(我的代码的简化版本)不起作用:


<?php

    $sxml = new SimpleXMLElement('<somexml/>');


    function foo(){

        $child = $sxml->addChild('child');

    }


    foo();

?>

为什么?我要访问,$sxml因为如果foo()失败,我想在上面记录错误。 foo()递归地调用自身以创建目录列表,因此我担心将整体传递给$sxml自身(如中所述foo($sxml))可能会损害性能。


有没有一种方法可以$sxml在$foo不传递参数的情况下访问内部?(PHP 5.2.x +)


编辑:如果代码看起来像这样呢?


<?php

    bar(){

        $sxml = new SimpleXMLElement('<somexml/>');

        function foo(){

            $child = $sxml->addChild('child');

        }

        foo();

    }

    bar();

?>


忽然笑
浏览 484回答 3
3回答

宝慕林4294392

您必须将其传递给函数:<?php&nbsp; &nbsp; $sxml = new SimpleXMLElement('<somexml/>');&nbsp; &nbsp; function foo($sxml){&nbsp; &nbsp; &nbsp; &nbsp; $child = $sxml->addChild('child');&nbsp; &nbsp; }&nbsp; &nbsp; foo($sxml);?>或将其声明为global:<?php&nbsp; &nbsp; $sxml = new SimpleXMLElement('<somexml/>');&nbsp; &nbsp; function foo(){&nbsp; &nbsp; &nbsp; &nbsp; global $sxml;&nbsp; &nbsp; &nbsp; &nbsp; $child = $sxml->addChild('child');&nbsp; &nbsp; }&nbsp; &nbsp; foo();?>如果变量不是全局变量,而是在外部函数中定义的,则第一个选项(作为参数传递)的作用相同:<?php&nbsp; &nbsp; function bar() {&nbsp; &nbsp; &nbsp; &nbsp; $sxml = new SimpleXMLElement('<somexml/>');&nbsp; &nbsp; &nbsp; &nbsp; function foo($sxml) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $child = $sxml->addChild('child');&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; foo($sxml);&nbsp; &nbsp; }&nbsp; &nbsp; bar();?>或者,通过在子句中声明变量来创建闭包use。<?php&nbsp; &nbsp; function bar() {&nbsp; &nbsp; &nbsp; &nbsp; $sxml = new SimpleXMLElement('<somexml/>');&nbsp; &nbsp; &nbsp; &nbsp; function foo() use(&$xml) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $child = $sxml->addChild('child');&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; foo();&nbsp; &nbsp; }&nbsp; &nbsp; bar();?>

catspeake

虽然最佳答案提供了一个不错的解决方案,但我想指出,大多数现代PHP应用程序中的适当解决方案是使用静态变量创建一个类,如下所示:<?phpclass xmlHelper {&nbsp; &nbsp; private static $sxml;&nbsp; &nbsp; public function getXML() {&nbsp; &nbsp; &nbsp; &nbsp; return self::$sxml;&nbsp; &nbsp; }&nbsp; &nbsp; public function setXML($xml) {&nbsp; &nbsp; &nbsp; &nbsp; self::$sxml = $xml;&nbsp; &nbsp; }}xmlHelper::setXML(new SimpleXMLElement('<somexml/>'));function foo(){&nbsp; &nbsp; $child = xmlHelper::getXML()->addChild('child');}foo();这种方法使您可以$sxml根据需要从内部进行访问foo(),但是与该global方法相比,它具有一些优势。使用此策略,您将始终能够在其中放置一个断点,setXML()以找出应用程序的哪个部分操纵了该值,而在操作全局变量时则无法做到这一点。您避免使用通用变量名污染全局名称空间sxml。
打开App,查看更多内容
随时随地看视频慕课网APP