I am confused about how the program is working; the code should print A, bB
but it is showing bA,B
class SampleClass {
public $a = "A";
protected $b = array ("a" => "A", "b" => "B", "c" => "C");
public function __get($v){
echo "$v";
return $this->b[$v];
}
}
$m = new SampleClass();
echo $m->a . ", " . $m->b;
This makes perfect sense really. Let's think about the execution order:
Before PHP can ECHO your requested string, it must evaluate it first (i.e. the $m->a . ", " . $m->b
part)
So at this point, the parser tries to resolve $m->a and $m->b, it resolves the first, but the 2nd fails, so we go to the magic method.
The magic method echos something (the first `b), and then resolves itself to B.
Now, we need to finish what we started (the original echo).
So what do we have?
combine it all together?
bA,B
This is odd isn't it but it isn't doing what you think it is doing.
Running this code does something different.
class SampleClass {
public $aaa = "A";
protected $b = array ("a"=> "A", "b" => "B", "c" => "C");
public function __get($v){
echo "$v";
return $this->b[$v];
}
}
$m = new SampleClass();
echo "[" . $m->a. ", ". $m->b. ", ". $m->c . "]";
Output is:
abc[A, B, C]
Your original __get does not get called when you do $m->a since there is a variable 'a' anyhow. It is only called as a last resort so you should write your own specific 'getter' function instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With