As I explained at the beginning of this tutorial, PHP 5 also includes a magic method called ”__clone(),” which is invoked automatically when using the “clone” keyword. For the sake of brevity, for now I’m going to say only that the “clone” keyword is used to create an independent copy of a specified object, instead of creating a reference to it. Now, returning to the “__clone()” magic method, it’s possible to give it a concrete implementation, in a way similar to the process performed with other magic functions discussed previously. To accomplish this, I’m going to reuse the “User” class that you saw in the previous section, which now will have the following definition: 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 undeclared 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 __clone( method public function __clone() { echo 'Cloning user object.'; } } In this particular case, I decided to give a trivial implementation to the above “__clone()” method to make it simpler for you to grasp, but naturally it can be set up to perform more complex tasks. However, despite how simple the “__clone()” method may look at first glance, it will be useful to demonstrate how it can be called by the PHP engine automatically when cloning an instance of the sample “User” class. If you wish to learn the full details of this process, though, you’ll have to read the last section of this tutorial.
blog comments powered by Disqus |
|
|
|
|
|
|
|