PHP魔法方法示例

前端之家收集整理的这篇文章主要介绍了PHP魔法方法示例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我从Zend PHP学习指南中得到这个问题,找不到正确的解释…
<?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->c;
?>

根据指南,解决方案应为“b,c,A,B,C,c:CC,b,C”.我不明白为什么 – 也许你这样做?我的意图是,首先调用$m-> a会导致结果“a”,但这显然是错误的…

由于__get()调用echo,所以在调用外部的echo之前,会输出一些数据.

用echo回到第一行,这是如何执行的:

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

此时,c已经被回显,现在显示值为A,Cm的字符串.

猜你在找的PHP相关文章