4
In PHP, according to the manual, the reference of one variable serves for a variable to point to the same place where the other is in memory. I also saw that when we declare references to a variable that does not exist, it is created and set to NULL
.
Hence arose a question.
We have the following codes.
In this assignment attempt below, an execution error will be generated.
$a = $b->b->c->d->e->f->g;
/*
Undefined variable 'a'
Trying to get property of non-object (6 vezes)
*/
var_dump($a, $b); // resultado: NULL NULL
Now, when we use the allocation operator by reference (&
), no error is generated, and the object (which does not exist) is magically created.
$a =& $b->b->c->d->e->f->g;
var_dump($a);
/*
a = NULL
*/
print_r($b);
/*
stdClass Object
(
[b] => stdClass Object
(
[c] => stdClass Object
(
[d] => stdClass Object
(
[e] => stdClass Object
(
[f] => stdClass Object
(
[g] =>
)
)
)
)
)
)
*/
- I’d like to know how this works internally, in the interpreter
of
PHP
. - It is recommended to create an object inside the other one this way (as I’ve seen it being used in an Dot Notation for PHP, but instead of an object, an array is used)?