Create __clone methord in PHP

Description

The following code shows how to create __clone methord.

Example


//from  w w w .  j  av a  2s  .  c o m
<?php
  class ObjectTracker
  {
    private static $nextSerial = 0;
    private $id;
    private $name;

    function __construct($name)
    {
      $this->name = $name;
      $this->id = ++self::$nextSerial;
    }

    function __clone()
    {
      $this->name = "Clone of $that->name";
      $this->id = ++self::$nextSerial;
    }

    function getId()
    {
      return($this->id);
    }

    function getName()
    {
      return($this->name);
    }
  }

  $ot = new ObjectTracker("Zeev's Object");
  $ot2 = clone $ot;

  //1 Zeev's Object
  print($ot->getId() . " " . $ot->getName() . "<br>");

  //2 Clone of Zeev's Object
  print($ot2->getId() . " " . $ot2->getName() . "<br>");
?>




















Home »
  PHP Tutorial »
    Language Basic »




PHP Introduction
PHP Operators
PHP Statements
Variable
PHP Function Create
Exception
PHP Class Definition