简体   繁体   English

通过引用传递变量创建所述变量

[英]Passing variable by reference creates said variable

function value(&$param){}

value($var['key']);
echo array_key_exists("key", $var)? "true" : "false"; //true

After running this code, $var['key'] ends up existing despite never being explicitly set. 运行此代码后,尽管从未显式设置$ var ['key'],但它仍然存在。 This means empty($var) will no longer return true , which kind of bothers me. 这意味着empty($var)将不再返回true ,这困扰着我。

Is this behavior intended? 这是故意行为吗? I couldn't find documentation on that. 我找不到有关的文档。


A simpler code that gives the same result : 给出相同结果的更简单的代码:

 $foo = &$bar['key']; $echo array_key_exists('key', $bar)? "true" : "false"; 

To pass by reference, there must be a reference to pass. 要通过引用传递,必须有一个引用传递。 To have a reference to pass, the variable must be created. 要引用传递,必须创建变量。 So having the variable created in your code above would be expected. 因此,应该在上面的代码中创建变量。

This would be similar to the situation with the built-in exec( $cmd, $out) where $out will exist even if $cmd produces no ouput. 这与内置exec( $cmd, $out)的情况类似,即使$ cmd不产生输出,$ out也将存在。

In your code you might try empty($var['key'] . 在您的代码中,您可以尝试empty($var['key']

Since you need to pass the variable to a function, the reference must be created first. 由于您需要将变量传递给函数,因此必须先创建引用。 In other languages you would get an error because the key does not exist and therefore cannot be passed to the function. 在其他语言中,您会收到错误消息,因为键不存在,因此无法传递给函数。 However, in PHP, there is no difference between creating a variable and using it. 但是,在PHP中,创建变量和使用变量之间没有区别。 Therefore, you are creating the key and then passing it, but the PHP syntax hides it from you. 因此,您先创建密钥,然后再传递它,但是PHP语法对您隐藏了它。

When executed by the PHP interpreted, this actually happens: 当由PHP解释执行时,这实际上发生了:

$var['key'] = null;
value($var['key']);

It is indeed a weird behavior from the interpreter. 从解释器的角度来看,这确实是一种奇怪的行为。 If the variable was passed by value it would generate a runtime error because it would not have been implicitly created. 如果该变量按值传递,则将生成运行时错误,因为不会隐式创建它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM