PHP magic methods example

陌路散爱 提交于 2019-12-04 18:19:06

问题


I have this question from the Zend PHP study guide and can't find a proper explanation...

<?php
    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;
?>

According to the guide, solution shall be "b,c,A,B,C,c: CC,b,c,A,B,C". I can't figure out why - maybe you do? My intention is that the first call of $m->a would lead to result "a", but that is obviously wrong...


回答1:


Since __get() calls echo, some data is being outputted before the echo outside of the class gets called.

Stepping through the first line with echo, this is how it gets executed:

$m->a   "A" is concatenated
","     "," is concatenated
$m->b   "b," is echoed, "B" is concatenated
","     "," is concatenated
$m->c   "c," is echoed, "C" is concatenated
"m"     "," is concatenated

At this point, b,c, has already been echoed, and the string with the value of A,B,Cm is now displayed.



来源:https://stackoverflow.com/questions/8451116/php-magic-methods-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!