PHP如何在这里避免无限递归? [英] How does PHP avoid infinite recursion here?
问题描述
考虑此类:
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()
.
I am overloading PHP's magic __set()
method. Whenever I set a property in an object of the test
class, it will call __set()
, which in turn calls other_set()
.
$obj = new test;
$test->prop = 10;
/* prints the following */
__set() called
other_set() called
但是other_set()
具有以下行$this->$name = $value
.这不应该导致对__set()
的调用,从而导致无限递归吗?
But other_set()
has the following line $this->$name = $value
. Shouldn't this result in a call to __set()
, causing infinite recursion?
我的理论是,仅当在类外设置内容时,它才会调用__set()
.但是,如果调用方法t()
,则可以清楚地看到它也通过__set()
.
I theorized that it would call __set()
only when setting things outside the class. But if you call the method t()
you can see it clearly goes through __set()
too.
推荐答案
__set
is only called once per attempt for a given property name. If it (or anything it calls) attempts to set the same property, PHP won't call __set
again -- it'll just set the property on the object.
这篇关于PHP如何在这里避免无限递归?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!