__get is not called if __set is not called, howeve

2019-04-28 11:00发布

问题:

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.