Unable to Access Global Variable Within Function
This script exhibits an issue where the global variable $sxml cannot be accessed within the foo() function:
$sxml = new SimpleXMLElement('<somexml/>'); function foo(){ $child = $sxml->addChild('child'); } foo();
Why This Occurs
Variables declared within the global scope cannot be directly referenced within functions unless they are explicitly defined as global within the function or passed as arguments.
Solutions
To access $sxml within foo(), there are several options:
function foo($sxml){ $child = $sxml->addChild('child'); } foo($sxml);
function foo(){ global $sxml; $child = $sxml->addChild('child'); } foo();
function bar() { $sxml = new SimpleXMLElement('<somexml/>'); $foo = function() use(&$xml) { $child = $sxml->addChild('child'); }; $foo(); } bar();
function bar() { $sxml = new SimpleXMLElement('<somexml/>'); function foo() { $child = $sxml->addChild('child'); } foo(); } bar();
The above is the detailed content of Why Can't I Access a Global Variable Inside a PHP Function?. For more information, please follow other related articles on the PHP Chinese website!