1

I just noticed the following behavior in my php code and I'm wondering why it's happening.

$array = array();

test_value($array['invalid_index']); // Error -> Notice: Undefined index: invalid_index in ...
test_reference($array['invalid_index']); //No error

function test_value($value){}
function test_reference(&$value){}

I was expecting both test_value and test_reference to throw the undefined index error but strangely the method by reference doesn't throw any error.

Why?

Gudradain
  • 4,653
  • 2
  • 31
  • 40

1 Answers1

5

Function parameters by-reference accept variables which haven't been declared previously; they are being declared by passing them as reference. This makes complete sense if you look at typical use cases of by-reference parameters:

$foo = preg_match('/(.)/', 'bar', $baz);

This function returns one value, which will be assigned to $foo. However, this function should also return the matches, which here is the third parameter $baz. Since a function can only return a single value at a time, additional "return" values are being realised by populating variables passed by reference.

If you had to pre-initialise these variables, your code would look like this:

$baz = null;
$foo = preg_match('/(.)/', 'bar', $baz);
echo $baz[0];

This makes code more complicated than necessary; PHP hence doesn't require that such variables "exist" beforehand.

deceze
  • 510,633
  • 85
  • 743
  • 889