0
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";
Estecka
  • 388
  • 1
  • 15
  • What is your `value` function doing? And why is `function funct(&$param){}` relevant in this example? – Maxime Jul 23 '17 at 02:42
  • 1
    @Maxime Ah, I messed up when writting the exemple. Value() and Funct() are actually the same thing. – Estecka Jul 23 '17 at 02:48

2 Answers2

0

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'].

cmerriman
  • 305
  • 1
  • 7
  • If this was the reasonning I would expect this from other situations: Run the same code with `function value($param){}` instead and the variable will not be created in the end, plus you'll get errors in the middle. – Estecka Jul 23 '17 at 02:53
  • Not the same thing since $param is not being passed by reference. $param is not created until the process is inside the function. – cmerriman Jul 23 '17 at 02:55
  • I don't understand why passing it by value makes it so different. In both cases $param requires a value that doesn't exist. – Estecka Jul 23 '17 at 04:38
0

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.

Maxime
  • 2,192
  • 1
  • 18
  • 23