Magic methods with accesible properties?

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
prueba2306
Forum Newbie
Posts: 2
Joined: Fri Apr 23, 2010 9:59 am

Magic methods with accesible properties?

Post 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?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Magic methods with accesible properties?

Post 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 />';
        }
        
    }
}
prueba2306
Forum Newbie
Posts: 2
Joined: Fri Apr 23, 2010 9:59 am

Re: Magic methods with accesible properties?

Post 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]
Post Reply