简体   繁体   English

PHP魔术__get和__set。 动态创建的字段是否被视为“可访问”?

[英]PHP magic __get and __set. Are dynamically created fields considered to be “accessible”?

I am somewhat new to PHP's OO system and the little quirks. 我对PHP的面向对象系统和小怪癖有点新鲜。 From what I have read the __get and __set methods are called when you accessing a field that is not "accessible". 根据我的阅读,当您访问不可“访问”的字段时,会调用__get和__set方法。 So, obviously accessing a public field or a protected field within the class will not call these functions. 因此,显然访问类中的公共字段或受保护字段将不会调用这些函数。 But what if I try to access $obj->a and a has never been defined before? 但是如果我尝试访问$ obj-> a并且a之前从未定义过怎么办? I originally thought this would call __get or __set but it seems it does not. 我原本以为这会调用__get或__set,但似乎没有。 I know to solve this is to put all the dynamically created fields into a data array. 我知道解决这个问题就是将所有动态创建的字段放入数据数组中。

Is $obj->a therefore a public field? $ obj->因此是公共领域吗? Thank you very much! 非常感谢你!

Example

  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?
$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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM