Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why there is no E_NOTICE error in the first call?

Tags:

php

I have a following code snippet:

 error_reporting(E_ALL | E_STRICT);

    function &getVal() {
       $data = [];

       return $data['hey'];
       //return $whatever; 
    }

    function getVal2() {
       $data = [];

       return $data['hey'];
    }

    var_dump(getVal());  // No E_NOTICE error is issued - why?
    var_dump(getVal2()); // E_NOTICE error is issued.

And the question is: Why there is no E_NOTICE error in the first call? The explanation is most likely that the variable $data['hey'] is created to return a reference. However, it still seems wrong not to issue an E_NOTICE error when $data['hey'] (or $whatever, ...) is not defined.

like image 483
Martin Vseticka Avatar asked Dec 17 '13 23:12

Martin Vseticka


1 Answers

It's expected behaviour

http://www.php.net/manual/en/language.references.whatdo.php#language.references.whatdo.assign

If you assign, pass, or return an undefined variable by reference, it will get created.

And some related "bugs":

https://bugs.php.net/bug.php?id=30350

Ok, it appears that the element is created because we are attempting to return a reference to something that does not exist.

https://bugs.php.net/bug.php?id=27627

When you try to access a non-existant array element you effectively create it, hence the NULL entries in the array.

like image 90
sectus Avatar answered Oct 21 '22 04:10

sectus