Welcome to my series on every PHP keyword and its usage. Today’s item: clone.

By default, the clone command will create a shallow copy of an object. This means that all primitive properties will be copied into a new object of the same type, but references will continue to reference the same object.

This behaviour can be modified in your own classes by implementing the __clone() magic method, which will be run on the cloned object immediately after that object is cloned.

Usage

1
2
3
4
5
6
<?php
$date = new DateTime();

// Clone the date to create a new date object which can be manipulated
// without affecting the initial date object
$newDate = clone $date;