PHP如何避免无限递归?

Con*_*nce 12 php recursion getter-setter

考虑这个课程:

class test
{
    public function __set($n, $v)
    {
        echo "__set() called\n";
        $this->other_set($n, $v, true);
    }

    public function other_set($name, $value)
    {
        echo "other_set() called\n";    
        $this->$name = $value;
    }

    public function t()
    {
        $this->t = true;
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在重载PHP的魔术__set()方法.每当我在test 类的对象中设置属性时,它将调用__set(),然后调用other_set().

$obj = new test;
$test->prop = 10;

/* prints the following */
__set() called
other_set() called
Run Code Online (Sandbox Code Playgroud)

但是other_set()有以下几行$this->$name = $value.这不应该导致调用__set(),导致无限递归吗?

我认为它__set()只会在课外设置时调用.但是,如果你打电话给这个方法,t()你也可以清楚地看到它__set().

cHa*_*Hao 12

__set每次尝试对给定的属性名称只调用一次. 如果它(或它调用的任何东西)试图设置相同的属性,PHP将不会__set再次调用- 它只是在对象上设置属性.