考虑这个类:PHP在这里如何避免无限递归?
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;
}
}
我重载PHP的魔术__set()
方法。无论何时我在test
类的对象中设置属性,它都会调用__set()
,然后调用other_set()
。
$obj = new test;
$test->prop = 10;
/* prints the following */
__set() called
other_set() called
但other_set()
有以下行$this->$name = $value
。不应该导致对__set()
的调用,导致无限递归?
我推理说只有在课外设置时才会调用__set()
。但如果你打电话给方法t()
,你可以看到它也清楚地通过__set()
。
这是正确的。如果有人想看到实现细节,它在'zend_object_handlers.c'中。 – Confluence 2012-04-04 20:14:44
@Confluence:谢谢......我想知道我在哪里阅读。 :)在手册中找不到它;我开始怀疑我是否想象它。但所有的测试证实了它,所以... – cHao 2012-04-04 20:38:11
这个答案很有用! – 2014-08-18 21:25:57