Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

__clone() Method

To clone an object is to create a new distinct object, from an existing one. This is basically a copy, although the object itself is multiplied by calling the clone operator.

By default PHP does a shallow clone, duplicating the scalars, like string, integer…, and keeping the same reference to objects. To make a deep clone, the class must define the __clone magic method.

Cloning is similar to creating another object of the same class, without requiring all the constructor arguments.

<?php

    $spike = new Dog('Spike', 'Teckel', 'red');
    $medor = clone $spike;
    
    $medor->setCollar('green'); // distinguish spike and medor by collar

?>

Documentation

See Also