Search code examples
phpgetter-setter

php output value does not match debugger value


So, I'd be OK (for now) with thinking that I misunderstand magic __get and __set in PHP. Fine.

But the output of this example is not only unexpected, it's also not matching what the debugger says is going to be output.

<?php
// put your code here
class Magic {
    public $a = 'A';
    public $x = 'X';
    protected $b = array("a"=>"A", "b"=>"B", "c"=>"C");
    protected $c = array(1,2,3);

    public function __get($v) {
        echo "$v,";
        return $this->b[$v];
    }
     public function set($var, $val) { 
        echo "$var: $val";
        $this->$var = $val;   
    }
}
$m = new Magic();
echo $m->a.",".$m->b.",".$m->c.",";

echo $m->x;
?>

The output of this is:

b,c,A,B,C,X

Now, I set up XAMPP and NetBeans just to debug this ... when I put a breakpoint on

echo $m->a.",".$m->b.",".$m->c.",";

and hover over that $m->a, I see

(string) A

But that's not what gets output? The first character to get output is

b

What's going on? The debugger says that $m->a has a value of A, but when we echo it, it outputs b


Solution

  • Seems like ZCE question)

    Line echo $m->a.",".$m->b.",".$m->c.","; means:

    1. Get value of $m->a. It is A. As debugger shows you.
    2. Get value of $m->b. You don't have public property b, so __get runs. It echoes b, (from line echo "$v,";) and returns B
    3. Get value of $m->c. You don't have public property c, so __get runs. It echoes c, (from line echo "$v,";) and returns C.
    4. Concatenate returned values ('A', 'B', 'C') with ,.

    So, before echoing result of concatenating two echos already done: b,c,. After that A,B,C string echoed