Is passing variables by reference deprecated?

折月煮酒 提交于 2019-12-22 06:53:02

问题


There is a comment on an answer on SO:

Code in answer:

$larry = & $fred;

Comment:

This is deprecated and generates a warning

But I don't think it is correct. Or is it?

So basically the question is:

can I copy a variable to another variable by reference?


回答1:


Depends on what type variable $fred is. If it's an object, it will be passed as reference a pointer to the object (thanks NikiC) will be passed as value anyway as of PHP 5, so there is no need to explicitly do it. Thus far, the comment is correct-ish.

For all other variable types, however, passing by reference needs to be explicitly specified and is not deprecated. Although it could be argued that it's usually not good programming practice to use a lot of references in PHP.




回答2:


Pretty sure it's not deprecated. I've been doing things like that a lot in PHP 5.3, basically to alias a deeply nested array. For example:

$short = &$a['really']['deep']['array']

When you do $a = $b and $a is an object it creates a "reference". This is best illustrated with an example:

>> $o = new stdClass()
stdClass::__set_state(array(
))
>> $o->a = 5
5
>> $o
stdClass::__set_state(array(
   'a' => 5,
))
>> $o2 = $o
stdClass::__set_state(array(
   'a' => 5,
))
>> $o2->a = 6
6
>> $o
stdClass::__set_state(array(
   'a' => 6,
))

Note that both $o->a and $o2->a are now 6, even though we only did the assignment on one of them.

When $a is a primitive (or scalar in PHP) such as string, int or float, it behaves a bit differently; the variable is copied:

>> $a = 1
1
>> $b = $a
1
>> $b = 2
2
>> $a
1

Note that $a is still 1.

When you use the ampersand, however, it basically works as an alias. Any changes to one variable will effect the other.

>> $c = 1
1
>> $d = &$c
1
>> $d = 2
2
>> $c
2

Note that $c is also 2 now.




回答3:


This might help: How does the '&' symbol in PHP affect the outcome?



来源:https://stackoverflow.com/questions/8274268/is-passing-variables-by-reference-deprecated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!