In case you haven’t had the chance to read the preceding article of this series, where I explained how to implement a simple destructor inside a class to create objects that are capable of persisting across several HTTP requests, below I reintroduced the full source code of this class, accompanied by a short example that shows how to use it. Here’s the corresponding code sample: // define 'User' class (implements the __destruct() magic method) class User { // constructor (not implemented) public function _construct(){}
// set undeclared property in a restrictive way public function __set($property, $value) { if (in_array($property, array('fname', 'lname', 'email')) === TRUE) { $this->$property = $value; } }
// get declared property public function __get($property) { if (isset($this->$property)) { return $this->$property; } }
// single point to fetch user data public function __call($method, $args) { if ($method === 'fetch' AND empty($args) === FALSE) { return $this->$args[0]; } } public function __destruct() { session_start(); $_SESSION['user'] = serialize($this); } } Apart from overloading properties and methods via the “__set()”, “__get()” and “__call()” functions, the above class also gives a simple implementation for its destructor, which saves an instance of any user object to a session variable right before being destroyed by the PHP interpreter. Of course, the previous code sample would be incomplete if I don’t create a script that shows how the destructor does its business. Here it is: // example on implementing the '__destruct()' magic method $user = new User(); $user->fname = 'Alejandro'; $user->lname = 'Gervasio'; $user->email = 'alejandro@mydomain.com'; Though it's a little bit rudimentary, this example depicts pretty clearly how to use the “__destruct()” method to create classes that can save themselves to a predefined storage mechanism, in this case a session variable. However, it’s possible to use a database or even a flat file to produce a similar result. Now that you’re pretty familiar with implementing destructors, it’s time to explore another magic function provided by PHP 5. So, in accordance with the concepts I expressed at the beginning, the last function that I’m going to cover in this series will be the popular “__autoload(),” which can be really useful for loading classes without having to code any PHP include statements explicitly. The implementation and use of this function will be discussed in detail in the following section. Thus, to learn more, please click on the link shown below and keep reading.
blog comments powered by Disqus |
|
|
|
|
|
|
|