Before demonstrating how to implement and use the "__sleep()" and "__wakeup()" functions when serializing/unserializing objects, I'm going to take an extra step and reintroduce the example developed in the previous installment of this series. It was aimed at illustrating how to overload a single method of a sample class by using the handy "__call()" magic method. Having explained that, here is the entire source code of the aforementioned example class, which is very simple to follow: 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]; } } } As depicted above, the previous "User" class gives a concrete implementation to the "__call()" function, in order to catch all of the calls made to an undeclared "fetch()" method. As you can see, the purpose of this is simply to retrieve the values assigned to the properties of the class by using only this single method. Finally, to help you understand more clearly how the overloaded "__call()" function does its thing, here's a short script that shows this process in an approachable fashion. Take a look at it, please: // example on utilizing 'User' class with method overloading $user = new User(); $user->fname = 'Alejandro'; $user->lname = 'Gervasio'; $user->email = 'alejandro@mydomain.com';
// display user data echo 'First Name : ' . $user->fetch('fname') . ' Last Name : ' . $user->fetch('lname') . ' Email : ' . $user->fetch('email');
/* display the following First Name : Alejandro Last Name : Gervasio Email : alejandro@mydomain.com */ See how simple it is to overload methods in PHP 5? I bet you do! In this particular case, even when the "fetch()" method hasn't been declared within the "User" class, each time the script calls it, it'll be intercepted by the "__call()" function, in this way avoiding the triggering of a fatal error. So far, so good. At this stage, you hopefully recalled how to use the "__call()" magic function to recreate a simple case of method overloading. Therefore, it's time to explore other magic functions. So, as I explained at the beginning, in the section to come I'm going to discuss how to use the "__sleep()" and "__wakeup()" functions when serializing and unserializing objects. To learn more on this topic, now click on the link below and keep reading.
blog comments powered by Disqus |
|
|
|
|
|
|
|