I came across the following code and could not figure out why the output of the script came out in a non-intuitive sequence using php's get and set magic methods.
class Magic
{
public $a = "A";
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 . ",";
$m->c = "CC";
echo $m->a . "," . $m->b . "," . $m->c;
Out put was:
bcA,B,C,c
CCbcA,B,C
First of all why is it no outputting A as the first thing? The sequence of output doesn't make sense.
The reason is quite simple. You do string concatenation so PHP has to prepare complete string before outputs one. It means that it executes everything that needs to be concatenated. When it executes getter
(__get
method will be called only for inaccessible members) there's echo
that is executed first and then returned value.
If you echo them out separately everything will be on its place.