无法访问函数内部的全局变量 [英] Can't access global variable inside function
问题描述
$ b
<?php
$ sxml =新的SimpleXMLElement('< somexml />');
函数foo(){
$ child = $ sxml-> addChild('child');
}
foo();
?>
为什么?我想访问 $ sxml
,因为如果 foo()
失败,我想在它上面记录错误。 foo()
会递归地调用它自己以创建一个目录列表,所以我担心把整个 $ sxml
传递给它自己在 foo($ sxml)
)可能会损害性能。
有没有办法访问 $ sxml
在 $ foo
里面,而不将它作为参数传递? (PHP 5.2.x +)
编辑:如果代码看起来像这样,实际上该怎么办?
<?php
bar(){
$ sxml = new SimpleXMLElement('< somexml />');
函数foo(){
$ child = $ sxml-> addChild('child');
}
foo();
}
bar();
?>
您必须将它传递给函数:
<?php
$ sxml = new SimpleXMLElement('< somexml />');
函数foo($ sxml){
$ child = $ sxml-> addChild('child');
}
foo($ sxml);
?>
或声明它全球:
<?php
$ sxml = new SimpleXMLElement('< somexml / >');
函数foo(){
global $ sxml;
$ child = $ sxml-> addChild('child');
}
foo();
?>
如果变量不是全局变量,而是在外部函数中定义的,则第一个选项)
<?php
function bar(){
$ sxml = new SimpleXMLElement('< somexml />');
函数foo($ sxml){
$ child = $ sxml-> addChild('child');
}
foo($ sxml);
}
bar();
?>
或者,建立一个中使用子句声明变量,可以在/ en / functions.anonymous.phprel =noreferrer> closure 中找到它。
pre $
<?php
function bar(){
$ sxml = new SimpleXMLElement('< somexml />');
函数foo()使用(& $ xml){
$ child = $ sxml-> addChild('child');
}
foo();
}
bar();
?>
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();
?>
You have to pass it to the function:
<?php
$sxml = new SimpleXMLElement('<somexml/>');
function foo($sxml){
$child = $sxml->addChild('child');
}
foo($sxml);
?>
or declare it global:
<?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:
<?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.
<?php
function bar() {
$sxml = new SimpleXMLElement('<somexml/>');
function foo() use(&$xml) {
$child = $sxml->addChild('child');
}
foo();
}
bar();
?>
这篇关于无法访问函数内部的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!