Search code examples
phpproxy-classesmagic-methodsobserver-pattern

PHP observer pattern / magic setter / proxing


I'm looking for a way to monitor when a variable in my class gets set.

For example if I have the following class:

class MyClass  {
    public $myVariable;
} 

And somewhere in my code I do:

$class = new MyClass();
$class->myVariable = "value";

I would like to be able to "hook" into the setter of myVariable. So when I call $class->myVariable = "Value"; a filter would start that checks if the new value equals "Value" and if so, throws an Exception.


Solution

  • define your attribute as private or protected, as usual.

    Then use the magic method __set() to catch the access.

    Best regards

    Raffael