As I stated in the previous segment, it’s possible to accomplish interesting and useful things with a destructor. In this case, I’m going to use it within the already familiar “User” class to create an object that will save itself to a session variable before being destroyed. How will this be achieved? Well, take a look at the enhanced definition of the “User” class, which now implements the “__destruct()” method. Here it is:
// 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); } }
As shown above, the implementation of the “__destruct()” method is very easy to follow. All it does is start or resume a new session, and then save an instance of the “User” class to a session variable. Period. Logically, nothing spectacular is happening here, except for the fact that all of these tasks will be performed before the instance of the user class gets destroyed. In this manner we're building an object that has the ability to maintain its state across different HTTP requests, by using only the PHP built-in session mechanism. Even though the definition of the “__destruct()” method is indeed self-explanatory, an example is in order her to understand how it works. Therefore, in the last section of this tutorial I’m going to set up such an example, so you can see how the destructor does its thing. To learn how this wrapping example will be created, click on the link shown below and keep reading. We’re almost done exploring destructors!
blog comments powered by Disqus |
|
|
|
|
|
|
|