Why does this code NOT throw out an undefined PHP property notification?

Just playing, and I found it.

Why does calling the link $this->newAxis() do not throw the declaration of the undefined property ( xAxis property), but var_dump() do?

 public function newXAxis() { // var_dump(isset($this->xAxis)); // false // var_dump($this->xAxis); // Throws the notice return $this->newAxis($this->xAxis); // Should throw the notice?! } protected function newAxis(&$current) { // ... } 

Does it have anything to do with passing by reference, so it does not have direct access to the property?

+7
source share
3 answers

Yes, this is because you pass it by reference. When you navigate by value, an attempt is made to really read the value of the variable - therefore, a notification appears. When you follow the link, the value does not need to be read.

When you do this, the variable / property is created if it does not already exist.

From manual :

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

 <?php function foo(&$var) { } foo($a); // $a is "created" and assigned to null 
+7
source
 newAxis(&$current) 

Follows the link. this means that you are passing a variable.

By default, all variables in PHP are undefined.

You define them simply using, for example,

 $a = 1; 

As you can see, PHP does not complain that $a is undefined, right?

Ok,), see here:

 $a = $b; 

PHP now complains that $b is undefined.

As with $a (you define a variable) and $b (a variable is not defined), it is passed by reference or by value:

 $this->newAxis($a); 

The $a variable is defined when passing by reference. It carries a default value of NULL . And now an example of $b :

 var_dump($b); 

var_dump takes values ​​by value. Therefore, PHP complains that $b is undefined.

And it's all. Hope this was clear enough.

+5
source

I'm here on a horse ...

Since you are accessing it as an object (from a class), it will not give you a notification, and when you var_dump something like your access to it, like an array (and since it is empty, it gives a notification)

-2
source

All Articles