引用还是变量?
一旦我在函数内部传递一个变量作为引用,如果我稍后访问它,它仍然是一个引用还是......?
示例:
function one(){
$variables = array('zee', 'bee', 'kee');
$useLater =& $variables;
two($variables);
}
function two($reference){
foreach($reference as $variable){
echo 'reference or variable, that is the question...';
}
}
在函数 two();
中,这里的变量是对先前设置的 $variables 的引用还是创建了一个新元素(我猜是在内存中......)?
另外,有没有一种方法可以检查变量是否通过引用传递? (如:is_reference();
)
Once I pass a variable inside a function as a reference, if I later access it, is it still a reference or..?
Example:
function one(){
$variables = array('zee', 'bee', 'kee');
$useLater =& $variables;
two($variables);
}
function two($reference){
foreach($reference as $variable){
echo 'reference or variable, that is the question...';
}
}
In function two();
are the variables here a reference to previously set $variables or a new element is created (in memory, I guess..)?
Plus, one more, is there a way to check if variable is passed by reference or not? (like: is_reference();
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
正如上面所定义的,函数二将使用
$reference
的新副本。要使用原始变量,您需要像这样定义函数二:
As defined above the function two will use a new copy of
$refernce
.To use the original variable you need to define function two like this:
如果您使用
&$foo
显式通过引用传递变量,则该变量仅通过引用传递(在当前版本的 PHP 中)。同样,当将变量声明为新变量时,例如$foo = $bar,$foo将是对$bar的引用,直到值发生变化。然后就是新的副本了。
这里有很多检测引用的方法,也许可以检查其中的一些。 (为什么你需要这样做尚不清楚,但它仍然存在)。
http://www.php.net/manual/en/language.references .spot.php
A variable is only passed by reference (in current versions of PHP), if you explicitly pass it by reference using
&$foo
.Equally, when declaring a variable to a new variable, such as
$foo = $bar
, $foo will be a reference to $bar until the value changes. Then it is a new copy.There are lots of ways of detecting a reference here, maybe check some of them out. (Why you would need to do this is unknown, but still, it is there).
http://www.php.net/manual/en/language.references.spot.php
多变的。 Look:
给出
,因此在
two()
中更改它不会在one()
中更改它,因此它是可变的。variable. look:
gives
so changing it in
two()
diesn't change it inone()
, so it's variable.如果你想让函数的参数作为引用,你必须写一个 & 。那里也有。
唯一的例外应该是对象。
If you want the parameter for the function to be a reference, you have to write an & there, too.
Only exception should be objects.
亲自尝试一下:
现在省略 & 符号,看看会发生什么。每次您打算如何传递相关变量时,您都需要明确告诉 PHP。
Just try it out for yourself:
Now leave out the &-sign and see what happens. You will need to tell PHP explicitly everytime how you intend to pass on the variable in question.