这样可以在对象上创建新属性.但是,有人可以通过支持链接解释为什么setAttrib以两种不同的方式表现?为什么不引起……等待它……堆栈溢出!! ??
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);
生产…
setAttrib
__set
setAttrib
object(Test)#1 (1) {
["hey"]=>
string(8) "It works"
}
编辑:我不是在寻找替代方案.我在寻找这个有效的原因.