php 通过引用传递差异
我在这里有一个简单的问题。在函数参数中通过引用传递变量(例如:)
function do_stuff(&$a)
{
// do stuff here...
}
和在函数内部执行变量(例如:
function do_stuff($a)
{
$var = &$a;
// do stuff here...
}
使用这两者之间有什么区别(如果有)?)之间有区别吗?另外,有人能给我一个很好的教程来解释通过引用传递吗?我似乎无法100%理解这个概念。
谢谢
I have a simple question here. Is there a difference between passing a variable by reference in a function parameter like:
function do_stuff(&$a)
{
// do stuff here...
}
and do it inside the function like:
function do_stuff($a)
{
$var = &$a;
// do stuff here...
}
What are the differences (if any) between using these two?. Also, can anybody give me a good tutorial that explains passing by reference? I can't seem to grasp this concept 100%.
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这里有一组示例,以便您可以了解每个问题会发生什么情况。
我还添加了第三个函数,它结合了您的两个问题,因为它也会产生不同的结果。
Here's a set of examples so you can see what happens with each of your questions.
I also added a third function which combines both of your questions because it will also produce a different result.
它们根本不等同。在第二个版本中,您创建对未定义变量
$a
的引用,导致$var
指向相同的 null 值。在第二个版本中对 $var 和 $a 所做的任何操作都不会影响函数之外的任何内容。在第一个版本中,如果您在函数内部更改 $a,则新值将在函数返回后出现在外部。
They're not at all equivalent. In the second version, you're creating a reference to an undefined variable
$a
, causing$var
to point to that same null value. Anything you do to $var and $a inside the second version will not affect anything outside of the function.In the first version, if you change $a inside the function, the new value will be present outside after the function returns.
在第一个示例中,如果您以任何方式修改函数内部的
$a
,函数外部的原始值也会被修改。在第二个示例中,无论您对
$a
或其引用$var
执行什么操作,都不会修改函数外部的原始值。In your first example, if you modify
$a
inside the function in any way, the original value outside the function will be modified as well.In your second example, whatever you do to
$a
or its reference$var
will not modify the original value outside the function.在第二个函数中,传入函数的
$a
是传入参数的副本(除非 $a 是对象),因此您正在创建一个$var
对函数内部$a
的引用,但它仍然与传递给函数的变量分开。假设您使用的是最新版本的 PHP,对象也会自动通过引用传递,因此这可能会有所不同。
In the second function, the
$a
passed into the function is a copy of the argument passed in, (unless $a is an object), so you are making a$var
a reference to the$a
inside the function but it will still be separate from the variable passed to the function.Assuming you are using a recent version of PHP, objects are automatically passed by reference too, so that could make a difference.