This (simplified version of my code) doesn't work:
<?php
$sxml = new SimpleXMLElement('<somexml/>');
function foo(){
$child = $sxml->addChild('child');
}
foo();
?>
Why? I want to access $sxml
because I want to log errors on it if foo()
fails. foo()
calls itself recursively to create a directory listing, so I fear passing the whole $sxml
onto itself (as in foo($sxml)
) could hurt performance.
Is there a way to access $sxml
inside $foo
without passing it as an argument? (PHP 5.2.x+)
EDIT: What if the code looks like this, actually?
<?php
bar(){
$sxml = new SimpleXMLElement('<somexml/>');
function foo(){
$child = $sxml->addChild('child');
}
foo();
}
bar();
?>
another solution is to use $GLOBALS while you declare that variable:
While the top answer provides a nice solution, I'd like to argue that the appropriate solution in most modern PHP applications is to create a class with a static variable, like so:
This approach allows you to access
$sxml
from withinfoo()
just like you wanted, but it has a few advantages over theglobal
approach.setXML()
to find out what part of your application has manipulated this value, which you cannot do when manipulating globals.sxml
.You have to pass it to the function:
or declare it global:
If the variable isn't global but is instead defined in an outer function, the first option (passing as an argument) works just the same:
Alternatively, create a closure by declaring the variable in a
use
clause.Use the global keyword to declare $sxml inside your function.
You need to explicitly invite the global variable into the functions scope: