Php Oops Cloning Objects Examples
PHP Object-Oriented Programming OOP cloning objects examples
object cloning using PHP's
Implementing Cloning in PHP Classes:
<?php
class MyClass {
public $data;
public function __construct($data) {
$this->data = $data;
}
// clone method
public function __clone() {
}
}
?>
Cloning Syntax:
<?php
$obj1 = new MyClass("Hello");
$obj2 = clone $obj1;
?>
__clone Method:
<?php
class MyClass {
public $property;
public function __clone() {
// Custom cloning
}
}
?>
Shallow vs Deep Copy with nested objects
<?php
public function __clone() {
$this->data = clone $this->data;
}
?>
Example Cloning in PHP
<?php
class MyClass {
public $data;
public function __construct($value) {
$this->data = $value;
}
public function __clone() {
// Perform deep copy if needed
$this->data = clone $this->data;
}
}
$obj1 = new MyClass(new stdClass());
$obj2 = clone $obj1;
?>