This manages to create a new property on the object. But, can someone explain, with supporting links, why setAttrib
behaves in two different ways? Why doesn't it cause a... wait for it... stack overflow!!??
class Test
{
public function setAttrib( $key, $value ) {
echo "setAttrib\n";
// first time: calls $this->__set($key, $value)
// second time: just sets a public property (but, when exactly was it created?)
$this->$key = $value;
}
public function __set( $key, $value ) {
echo "__set\n";
$this->setAttrib($key, $value);
}
}
$test = new Test();
$test->setAttrib('hey', 'It works');
var_dump($test);
produces...
setAttrib
__set
setAttrib
object(Test)#1 (1) {
["hey"]=>
string(8) "It works"
}
Edit: I'm not looking for an alternative. I'm looking for the reason why this works.