Passing variable by reference creates said variable

50 Views Asked by At
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. This means empty($var) will no longer return true, which kind of bothers me.

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";
2

There are 2 best solutions below

3
On

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.

In your code you might try empty($var['key'].

0
On

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. Therefore, you are creating the key and then passing it, but the PHP syntax hides it from you.

When executed by the PHP interpreted, this actually happens:

$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.