Page 1 of 1

Can I call a method when an object's property value changes?

Posted: Tue Mar 23, 2010 3:21 am
by dan.lugg
I'm looking for an alternative to this:

Code: Select all

 
 
class MyClass{
    private $myProperty;
 
    private function someMethod($val){
        //do something to $val
        return $val;
    }
 
    public function setMyProperty($val){
        if(isset($val)){
            $this->myProperty = self::someMethod($val);
        }else{
            return false;
        }
    }
 
 
Instead of forcing the value of $myProperty to be changed via the setter method (thus calling the someMethod function on the value) is there another manner to do this? Something that would be syntactically similar to the following?

Code: Select all

 
 
class MyClass{
    public $myProperty;
 
    private function someMethod($val){
        //do something to $val
        return $val;
    }
 
    public function myProperty(){ //called whenever the value of $myProperty is changed
        $this->myProperty = self::someMethod($this->myProperty);
    }
}
 
 
Any ideas, feedback.. anything is appreciated :) (This falls into the category of "overloading", does it not?)

Re: Can I call a method when an object's property value changes?

Posted: Tue Mar 23, 2010 3:32 am
by requinix
Not like that, no, but you can implement __get and __set.

Re: Can I call a method when an object's property value changes?

Posted: Tue Mar 23, 2010 12:12 pm
by dan.lugg
Yes I understand that the magic methods can be used, but they would only work if the properties haven't been declared, correct?

Re: Can I call a method when an object's property value changes?

Posted: Tue Mar 23, 2010 12:14 pm
by pickle
No, they're invoked whenever an object property is referenced from outside the object, that cannot be accessed. So, if you've got a private object property, or one that doesn't exist, __get() and __set() will be invoked.