Reputation: 48459
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?
Upvotes: 7
Views: 245
Reputation: 198204
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.
Upvotes: 5
Reputation: 78731
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
Upvotes: 7
Reputation: 2338
I'm going on a limb here...
Since you are accessing it as an object (from a class) it won't give you a notice, while when you var_dump something it kind of access it like an array (and since it's empty it throws a notice)
Upvotes: -2