How to clone objects in PHP

When you have an object you can clone it using the clone keyword:

class Dog {
  public $name;
}

$roger = new Dog();
$roger->name = 'Roger';

$syd = clone $roger;

This performs a shallow clone, which means that references to other variables will be copied as references - there will not a “recursive cloning” of them.

To do a deep clone you will need to do some more work.

Download my free PHP Handbook!