1

我对 PHP 的 OO 系统和小怪癖有些陌生。根据我的阅读,当您访问不可“访问”的字段时,会调用 __get 和 __set 方法。因此,显然访问类中的公共字段或受保护字段不会调用这些函数。但是如果我尝试访问 $obj->a 并且之前从未定义过 a 怎么办?我最初认为这会调用 __get 或 __set 但似乎没有。我知道解决这个问题的方法是将所有动态创建的字段放入一个数据数组中。

$obj->a 因此是一个公共字段吗?非常感谢你!

例子

  class Example
  {
    public function __get($field)
    {
      echo 'Getting ' . $field;
      return $this->$field; 
    }

    public function __set($field, $value)
    {
      echo 'Setting ' . $field . ' to ' . $value;
      $this->$field = $value;
    }
   }

   $obj = new Example;
   $obj->randomField = 1; //here randomField is set to 1 but the echo statement is not printed out in __set
   echo $obj->randomField;  //here, 1 will be echoed but not the statement in __get

   //is randomField a public field?
4

1 回答 1

3
$obj = new Example;
$obj->randomField = 1; // here __set method is called
echo $obj->randomField; // here __get method won't be called because `$obj->randomField` exists.

//is randomField a public field?
// Yes, after you set it, it became a public field of the object.
于 2012-06-08T02:38:10.343 回答