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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dan.lugg
Forum Newbie
Posts: 4
Joined: Thu Dec 03, 2009 4:15 pm

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

Post 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?)
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

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

Post by requinix »

Not like that, no, but you can implement __get and __set.
dan.lugg
Forum Newbie
Posts: 4
Joined: Thu Dec 03, 2009 4:15 pm

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

Post 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?
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

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

Post 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.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply