Search code examples
phpoopmagic-methods

Magic Method in PHP for triggering method when a declared property is set?


I have a class with declared properties. The whole point of the class and it's extensions is that I need them to always be available, even if null, on a different object. So it looks like:

class Wrapper {

     public $a = "";
     public $b = "";
     public $c = "";

    public function Wrapper() {

        $this -> wrapped = new Wrapped();

        foreach($this as $key => $val) {
              if($key != 'wrapped') {
                 $this -> wrapped -> $key = $val;
              }
        }

    }
}

But after instantiating the object, I want to be able to overwrite the declared values directly, so:

 $wrap_test = new Wrapper();
 $wrap_test -> a = 12;

So rather than writing a method or using $wrap_test -> wrapped -> a -> 12, I was looking for an equivalent to __set() that would call a method whenever any property is set.

Does this exist?


Solution

  • If your properties are declared public, there's no "event" or other method you can hook into. The properties can simply be changed directly by anybody.

    Declare your properties as protected or private so they cannot be changed directly from outside the class, then implement the __get and __set methods so you are able to access the properties as if they were public. In the __set method, do whatever you need to do when the property changes.