__clone in PHP 5



When using OO PHP there sometimes becomes the need to duplicate an object. If a new object has been instantiated and methods have been used to populate its properties, there may be a need to create a duplicate of the current version of that object for separate usage. 


Example __Clone Usage

In the example below the ‘WebDeveloper’ object is made and the name is set using the __set magic method. A clone is then made of the ‘WebDeveloper‘ object and saved into its own variable (when ‘clone’ is used the ‘__clone’ is automatically called within the class). The __set method is then used to reset the ‘name‘ property to something different, in this case ‘Jordizle’. 

  class WebDeveloper {
    public $info = array();
    public function __set($item, $value) {
      $this->info[$item] = $value;
    public function __clone() {
      $clonedObject = new WebDeveloper();
      foreach ($this->info as $property) {
        $clonedObject->info[$property] = $property;
      return $clonedObject;
  $developer = new WebDeveloper();
  $developer->__set(‘name’, ‘Jordizle’);
  $anotherDeveloper = clone $developer;
  $anotherDeveloper->__set(‘name’, ‘Jordan’);

Your comments.