Calling a concrete method before destroying an object: introducing class destructors In the previous section, you learned how to build a simple class that didn’t define a destructor method inside its API, which could be necessary under certain conditions. Of course, I’m not saying that from this point onward each class you work with must declare a destructor, because this would be pointless. However, let me show you a modified version of the “User” class that you learned before. This time I will include a very primitive “__destruct()” method. Please study the brand new definition of the class in question: // basic example on using a '__destruct()' method // define 'User' class class User{ private $firstName; private $lastName; private $email; public function __construct($firstName,$lastName,$email){ if(!$firstName||strlen($firstName)>32){ throw new Exception('Invalid First Name parameter!'); } if(!$lastName||strlen($lastName)>32){ throw new Exception('Invalid Last Name parameter!'); } if(!$email||!preg_match("/^.+@.+..+$/",$email)){ throw new Exception('Invalid Email parameter!'); } $this->firstName=$firstName; $this->lastName=$lastName; $this->email=$email; } // get user's first name public function getFirstName(){ return $this->firstName; } // get user's last name public function getLastName(){ return $this->lastName; } // get user's email public function getEmail(){ return $this->email; } // get all user data public function getAll(){ return 'First Name: '.$this->firstName.' Last Name: '.$this->lastName.' Email Address: '.$this->email; } // implement a __destruct()' method public function __destruct(){ echo '<h2>Destroying user now...<h2>'; } } As you can realize, defining a destructor for a determined PHP 5 class isn’t rocket science; the whole process is reduced to defining a “__destruct()” method, and then implementing it correctly. In this case, my destructor is actually very primitive and will display the message “Destroying user now…” before the corresponding object is destroyed. So far, so good. At this point, you've grasped the basics of defining a destructor within the previous “User” class, something that hopefully has caught your attention. Therefore, I'm going to create a test example, aimed at demonstrating the limited functionality of the destructor we just created. To see how this brand new example will be developed, please visit the next section and keep reading.
blog comments powered by Disqus |
|
|
|
|
|
|
|