aw *_*rud 4 php pointers pass-by-reference
编写调用接受变量指针并更改值的函数的代码的正确方法是什么?
以下工作,但我的 IDE 抱怨 $v 是一个未定义的变量,直到它调用的函数设置一个值:
function foo(&$bar) {
$bar = 12345;
}
foo($v);
Run Code Online (Sandbox Code Playgroud)
我应该先初始化 $v 以满足我的 IDE 吗?或者有没有更好的方法来做到这一点?
$v = NULL;
foo($v);
Run Code Online (Sandbox Code Playgroud)
When passing a variable by reference to a function, you need to have a reference to the variable from the calling code. To have a reference, the variable needs to exist. To exist, the variable needs to be initialized.
我建议将其设置为合理的默认值。如果合理的默认值是null,则使用null. 在某些情况下,使用''或0取决于您希望变量保存什么类型的值可能更合理。