14. 引用只允许定义在函数参数中,实时传递引用是禁止的。例如:// 引用定义在函数参数-允许的function defineRefInMethod(&$a){ $a = 'a';} defineRefInMethod($b);echo $b; // 'a'// 实时传递引用-禁止的function callTimePassRef($a){ $a = 'a';}callTimePassRef(&$c);echo $c; // 'a'
What are the scenarios for each of the above two cases?
Reply content:
14. 引用只允许定义在函数参数中,实时传递引用是禁止的。例如:// 引用定义在函数参数-允许的function defineRefInMethod(&$a){ $a = 'a';} defineRefInMethod($b);echo $b; // 'a'// 实时传递引用-禁止的function callTimePassRef($a){ $a = 'a';}callTimePassRef(&$c);echo $c; // 'a'
What are the scenarios for each of the above two cases?
Sometimes we handle arrays like this.
$arr = [...];foreach($arr as &$value){ // do something here...}print_r($arr);
1, the former is the transmission address, the latter is the value. The former changes to & modified variables in the function body produce global changes, while the latter does not. A function can have only one return value, typically using the return value when making changes to a single variable, and only using & when making changes to multiple variables.
2. References are allowed only in function parameters. This sentence is doubtful, it is not known where the source is, and the second half of the sentence is an incredible explanation.
In fact, the second usage will be an error.
If you do not make an error, it is also a very wonderful way of writing, because the address is read-only non-writable.