Page 1 of 1

Magic methods with accesible properties?

Posted: Fri Apr 23, 2010 10:20 am
by prueba2306
Hello people:

This topic is about "magic methods" for accesible properties:

Many of you know about __set, __get, __isset, __unset and the behaviour that these functions have inside an object. For example we have this class:

Code: Select all

class MyClass {
    public $name;

    public $age;

    public function __set($name, $value) {
        echo 'created ' . $name . ' = ' . $value . '<br />';
    }
}
and if i do this:

Code: Select all

$obj = new MyClass();
$obj->age = '19';
$obj->sex = 'woman';
$obj->name = 'Natasha';
i get this:
[text]created sex = woman[/text]

Fine, nothing new under the sun. But, this is the question: is there any "magic method" for the defined properties so i can have these result?
[text]
changed age = 19
created sex = woman
changed name = Natasha[/text]

If not, how would you handle this issue? I'm thinking about "get" and "set" functions and define my own "magic method" to invoke inside of them.

What do you think?

Re: Magic methods with accesible properties?

Posted: Fri Apr 23, 2010 10:25 am
by John Cartwright
Generally, you would implement some kind of data container, instead of manipulating the properties directly. From there, you can simply check whether the key exists.

Code: Select all

class MyClass {

    protected $_data = array();

    public function __set($name, $value) {

        if (isset($this->_data[$name])) {
            echo 'changed' . $name . ' = ' . $value . '<br />';
        } else {
            echo 'created ' . $name . ' = ' . $value . '<br />';
        }
        
    }
}

Re: Magic methods with accesible properties?

Posted: Fri Apr 23, 2010 10:54 am
by prueba2306
Good answer, I used your class (I add a missing instruction):

Code: Select all

class MyClass {
    protected $_data = array();

    public function __set($name, $value) {

        if (isset($this->_data[$name])) {
            echo 'changed ' . $name . ' = ' . $value . '<br />';
        } else {
            echo 'created ' . $name . ' = ' . $value . '<br />';
            $this->_data[$name] = true;
        }
   
    }
}
With these instructions:

Code: Select all

$obj = new MyClass();
$obj->age = '19';
$obj->sex = 'woman';
$obj->name = 'Natasha';
$obj->age = '20';
and I get the next thing:
[text]created age = 19
created sex = woman
created name = Natasha
changed age = 20[/text]