How does PHP avoid infinite recursion here?

寵の児 提交于 2019-11-30 09:01:18

__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.

From the documentation:

__set() is run when writing data to inaccessible properties

For example:

class foo {
  private $attributes;
  public $bar;

  public function __construct() {
    $this->attributes = array();
  }

  public function __set($n, $v) {
    echo "__set() called\n";
    $this->attributes[$n] = $v;
  }
}

$x = new foo;
$x->prop = "value";
$x->attributes = "value";
$x->bar = "hello world";

In this case, $x->prop is inaccessible and __set will be called. $x->attributes is also inaccessible, so __set will be called. However, $x->bar is publicly accessible, so __set will not be called.

Similarly, in the __set method, $this->attribtues is accessible, so there is no recursion.

In your example code above, $this->$name is accessible in the scope in which its called, therefore __set is not called.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!