__get is not called if __set is not called, however code works?

守給你的承諾、 提交于 2020-01-02 04:01:26

问题


Here is my code:

<?php

class SampleClass {

    public function __get($name){
        echo "get called";
        echo $name;
    }

    public function __set($name, $value) {
        echo "set called";
    }

}

?>

And my index file:

$object = new SampleClass();
$object->color = "black";
echo $object->color;

If I run this code as it is, here is the output:

set calledget calledcolor

However if I comment out

public function __set($name, $value) {
    echo "set called";
}

the part above (only this part), then the output will be:

black

So what happened here?


回答1:


This is an explanation of what is happening. In your first example. You never stored the value within the object, nor did a declared property exist. This, echo $object->color; never actually does anything as nothing is returned from __get.

In your second example, you assigned a value to a property in your object. Since you did not declare the property in your object, it gets created by default as public. Since its public, __get is never called when accessing it.




回答2:


__get will only be called is no property exists. By removing __set, you create a property when setting, so instead of calling __get, php just returns the property.

A simple way to think about it is that __get and __set are error handlers - They kick in, when php can't otherwise honor your request.



来源:https://stackoverflow.com/questions/14571565/get-is-not-called-if-set-is-not-called-however-code-works

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