As I explained in the introduction, PHP 5 also includes a pair of complementary magic functions called "__sleep()" and "__wakeup()," which are transparently invoked when an object is being serialized and unserialized respectively. In theory, these functions should be very easy to grasp, but it'd be even better to back up these concepts with some illustrative examples. So, below I redefined the "User" class that you saw before by giving a basic implementation to the "__sleep()" and "__wakeup()" methods. Take a look at the class's source code, which now looks like this: 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]; } }
// implement __sleep() method public function __sleep() { echo 'Serializing user object'; return array('fname'); }
// implement __wakeup() method public function __wakeup() { echo 'Unserializing user object'; } } Now, apart from using the already familiar "__call()" function, the above "User" class also gives a concrete implementation of the "__sleep()" and "__wakeup()" methods. It's admittedly very trivial, since they'll only display a message on the browser when being called by the PHP engine. Despite the simplicity of this particular example, it should be useful enough to demonstrate how to utilize the "__sleep()" and "__wakeup()" functions within a class. However, the "User" class itself won't do anything useful until an instance of it is serialized or unserialized, since the mentioned magic methods will be called upon the occurrence of these specific events. So, it's necessary to create a script that performs these tasks in a simple manner. Thus, in the last section of this tutorial I'm going to develop a wrapping example that will show what happens when an instance of the previous "User" class in serialized and unserialized sequentially. To learn how this final example will be created, click on the link that appears below and read the following section.
blog comments powered by Disqus |
|
|
|
|
|
|
|