Object Cloning

To make a copy of an object , __clone() method should be used.

<?php
class foo {
     var $bar;
    function baz($val) {
        $this->bar = $val;
    }
}

$a = new foo();

$b = clone $a; // make $b contain a separate copy of $a

$a->baz(2);

var_dump($b->bar != $a->bar); // True

?>

You can specify your own __clone() method that will be executed when an object is cloned.

<?php
class foo {
     var $bar, $is_clone = 0;
    function baz($val) {
        $this->bar = $val;
    }
    function __clone()
    {
        $this->is_clone = 1;
    }
}

$a = new foo();
$b = clone $a; // make $b contain a separate copy of $a

echo $b->is_clone; // will print 1
?>

 


Loading ...

Related Results :

  1. Object Cloning
Note :
  • Related Posts are generally User Blog posts.
  • or Other tutorials from other networks of w3clan.com.
  • Any registered user can create related posts based on search term tags.

About the Author