PHP includes a brilliant concepts called overloading which means you can try to get and set undefined properties as well as run undefined methods. In this little tutorial I will show you how to handle overloadable properties. Every time an undefined property is accessed, the object will try the magic methods __set() and __get() instead of just returning an error right away. If they are defined, it works. Consider the following example class:
class Magic { var $data = array(); function __construct($data) { foreach ($data as $key => $value) $this->$key = $value; } function __set($key, $value) { $this->data[$key] = $value; } function __get($key) { if (isset($this->$key)) return $this->data[$key]; } function __isset($key) { if (isset($this->data[$key])) return true; else return false; } function __unset($key) { if (isset($this->$key)) unset($this->data[$key]); } }
You can use this class to extend other classes with this basic property overloading, to store properties inside the data variable:
class Person extends Magic { function getName() { return $this->first_name.' '.$this->last_name; } }
Now you can do all of the following nice stuff:
$data = array( 'first_name' => 'John', 'last_name' => 'Doe', ); $person = new Person($data); echo $person->getName(); $person->first_name = 'John'; $person->last_name = 'Doe'; isset($person->first_name) unset($person->first_name)
Check out more in the PHP manual.
No comments yet (leave a comment)