Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this code is NOT throwing an undefined property PHP notice?

Just playing around and I found this.

Why the call by reference to $this->newAxis() does not throw an undefined property notice (xAxis property), while the var_dump() does?

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 something to do with the passing by reference, thus not accessing the property directly?

like image 721
gremo Avatar asked Dec 21 '12 01:12

gremo


2 Answers

Yes, it happens because you pass it by reference. When you pass by value, an attempt is made to actually read the value of the variable - so a notice appears. When you pass by reference, the value does not need to be read.

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

From the manual:

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

<?php
function foo(&$var) { }
foo($a); // $a is "created" and assigned to null
like image 112
kapa Avatar answered Oct 03 '22 22:10

kapa


newAxis(&$current)

is pass by reference. that means you are passing a variable.

By default all variables in PHP are undefined.

You define them by just using, e.g.

$a = 1;

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

Okay ;), see here:

$a = $b;

PHP now complains that $b is undefined.

Like with $a (you define the variable) and $b (the variable is not defined) it is with passing by reference or by value:

$this->newAxis($a);

The variable $a is defined when passed by reference. It carries it's default value NULL. And now the $b example:

var_dump($b);

var_dump takes it's parameters by value. Therefore PHP complains that $b is not defined.

And that's all. I hope it was clear enough.

like image 29
hakre Avatar answered Oct 03 '22 23:10

hakre