Answer the question
In order to leave comments, you need to log in
Why does it happen when assigning a value to a property of an object in it?
I was learning php and came across one example.
Why if you assign an array property to an object , then it is inside the $test variable.
If it 's a normal property , then it's outside the $test variable.
<?php
class Foo {
public $test = [];
public function & __get($name) {
return $this->test[$name];
}
public function out() {
return $this;
}
}
$foo = new Foo();
$foo->arr[1] = 'one';
$foo->arr[2] = 'two';
$foo->str = 'three';
echo '<pre>';
print_r($foo->out());
print_r($foo->arr);
Foo Object
(
[test] => Array
(
[arr] => Array
(
[1] => one
[2] => two
)
)
[str] => three
)
Array
(
[1] => one
[2] => two
)
object(Foo)#1 (2) {
["test"]=>
array(1) {
["arr"]=>
array(2) {
[1]=>
string(3) "one"
[2]=>
string(3) "two"
}
}
["str"]=>
string(5) "three"
}
array(2) {
[1]=>
string(3) "one"
[2]=>
string(3) "two"
}
Answer the question
In order to leave comments, you need to log in
php.net/references.return
First, I'll describe the first part of this expression - $foo->arr
:
You are accessing a property arr
, but it doesn't exist, so the call is "hooked" by the __get
. It accesses the property test
using as the array key the name (arr) given as the parameter. Then it returns you a link ( php.net/references.return ) to the $this->test['arr'];
second part - [1] = 'one'
:
to access the array element with index 1 of the property obtained earlier by reference. That is, writing $foo->arr[1]
after reference resolution is equivalent $this->test['arr'][1]
from within the object. Further there is an assignment of a line, it turns out $this->test['arr'][1] = 'one';
Why 'three'
out of an array test
?
because$foo->str = 'three';
here you don't get caught in __get(). This is not getting (get) a property, but setting (set) its value.
PS The
example is really brain-breaking. It is better not to use such things as a return by reference, and even in combination with a magic method.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question