Gudradain Gudradain - 1 year ago 78
PHP Question

PHP - Passing by reference suppress undefined index error?

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
to throw the undefined index error but strangely the method by reference doesn't throw any error.


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download