简体   繁体   English

魔术方法__get和__set - 来自ZCE的例子

[英]Magic methods __get and __set - example from ZCE

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.",";

This is an example question (not from an actual exam) for ZCE. 这是ZCE的一个示例问题(不是来自实际考试)。 Can someone please explain to me... what's going on here, and why the answer is... not at all what I expected? 有人可以向我解释......这里发生了什么,为什么答案是......根本不是我所期待的?

b, c, A, B, C,c: CC,b, c, A, B, C,

then… what do you expect? 那么......你期待什么?

It calls __get / __set if you don't have from your actual scope the rights to access the property / the property doesn't exist. 如果您没有从实际范围访问该属性/该属性的权限不存在,则调用__get / __set

So $m->a gets directly "A"; 所以$m->a直接获得“A”; $m->b and $m->c call first __get("b") and __get("c") (return "B" and "C" after echoing "b, c, ") $m->b$m->c先调用__get("b")__get("c") (在回显“b,c”后返回“B”和“C”)

The same is for $m->c = "CC"; $m->c = "CC"; : it calls __set("c", "CC") as $c is a protected (non-accessible) property. :它调用__set("c", "CC")因为$c是受保护(不可访问)的属性。 (sets $m->c to "CC" after echoing "c: CC") (在回显“c:CC”后将$ m-> c设置为“CC”)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM