The best way to understand how the “__clone()” method is called by the PHP interpreter is by means of a concrete example that shows how to clone an instance of the sample “User” class. I developed a small script which uses the “clone” keyword to clone an user object, in this way triggering a call to the pertinent “__clone()” method. The definition of this example script is as follows: $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'); /* displays the following First Name : Alejandro Last Name : Gervasio Email : alejandro@mydomain.com */
// clone user object $newuser = clone $user; /* displays the following Cloning user object. */ Simple to code and read, right? As you can see, once the script spawns an object from the “User” class and creates some undeclared properties, it clones this object. This process automatically calls the pertinent “__clone()” method. As with other magic functions reviewed before, this specific method supports a more complex and useful implementation. So, if the magic functions bundled with PHP 5 have already caught your attention, you might want to sharpen your programming skills by playing with this method a bit when cloning objects. The experience will be really instructive, trust me. Final thoughtsOver this fifth chapter of the series, I discussed how to implement and use the “__clone()” magic method, which as you saw earlier, is invoked automatically when an object is cloned via the “clone” keyword. In the penultimate installment of the series, I’m going to explore in depth another helpful magic method provided by PHP 5, probably one that you’ve used many times before when creating your classes. In this specific case, I’m talking about the handy “__destruct()” method, which is called by the PHP interpreter before an object gets destroyed at the end of a script. Want to learn how to use this method? Then don’t miss the next tutorial!
blog comments powered by Disqus |
|
|
|
|
|
|
|