In PHP, it can be easily done using clone
class Sheep {
protected $name;
protected $category;
public function __construct(string $name, string $category = 'Mountain Sheep') {
$this->name = $name;
$this->category = $category;
}
public function setName(string $name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function setCategory(string $category) {
$this->category = $category;
}
public function getCategory() {
return $this->category;
}
}
Then it can be cloned like below
$original = new Sheep('Jolly');
echo $original->getName(); // Jolly
echo $original->getCategory(); // Mountain Sheep
// Clone and modify what is required
$cloned = clone $original;
$cloned->setName('Dolly');
echo $cloned->getName(); // Dolly
echo $cloned->getCategory(); // Mountain sheep
Also you could use the magic method __clone
to modify the cloning behavior.
When to use?
When an object is required that is similar to existing object or when the creation would be expensive as compared to cloning.