I used the global declaration and it works.
You have to pass it to the function:
1 2 3 4 5 6 7 8 9 |
<?php $sxml = new SimpleXMLElement('<somexml/>'); function foo($sxml){ $child = $sxml->addChild('child'); } foo($sxml); ?> |
or declare it global:
1 2 3 4 5 6 7 8 9 10 |
<?php $sxml = new SimpleXMLElement('<somexml/>'); function foo(){ global $sxml; $child = $sxml->addChild('child'); } foo(); ?> |
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:
1 2 3 4 5 6 7 8 9 10 |
<?php function bar() { $sxml = new SimpleXMLElement('<somexml/>'); function foo($sxml) { $child = $sxml->addChild('child'); } foo($sxml); } bar(); ?> |
Alternatively, create a closure by declaring the variable in a use
clause.
1 2 3 4 5 6 7 8 9 10 |
<?php function bar() { $sxml = new SimpleXMLElement('<somexml/>'); function foo() use(&$xml) { $child = $sxml->addChild('child'); } foo(); } bar(); ?> |