0

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.

Peeter
  • 9,282
  • 5
  • 36
  • 53

1 Answers1

2

define your attribute as private or protected, as usual.

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

Best regards

Raffael

Raffael
  • 19,547
  • 15
  • 82
  • 160
  • Forcing the use of private properties just to implemented some validation isn't correct in my opinion (especially if the private keyword is more or less overwritten). It's a working work-around but unfortunetly does not satisfy my need. – Peeter Feb 07 '11 at 11:20
  • what? that's a standard-OOP-paradigm ... I don't get your point – Raffael Feb 07 '11 at 11:20
  • 1
    Setting a property as private and then allowing access to it from outside the class later on. – Peeter Feb 07 '11 at 11:29