Consider this class:
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;
}
}
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
But other_set() has the following line $this->$name = $value. Shouldn’t this result in a call to __set(), causing infinite recursion?
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.
__setis 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__setagain — it’ll just set the property on the object.