1
votes

I am somewhat new to PHP's OO system and the little quirks. From what I have read the __get and __set methods are called when you accessing a field that is not "accessible". 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? I originally thought this would call __get or __set but it seems it does not. I know to solve this is to put all the dynamically created fields into a data array.

Is $obj->a therefore a public field? 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?
1
The echo in the __set will be printed out, what is the problem?xdazz
"Is $obj->a therefore a public field?" Yes, as your example shows...Matthew
I know from experience that "dynamic" properties have public visibility, but I searched in vain for a PHP manual quotation that says so.John Flatness
so __get and __set are called for already defined protected and private fields?Koray Tugay

1 Answers

3
votes
$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.