Source Code:
(back to article)
<?php // Example 1 class Car { public $make; public $model; public $year; public function __construct($make, $model, $year) { $this->make = $make; $this->model = $model; $this->year = $year; } public function __clone() { $this->year = null; } } $myCar = new Car("Ford", "Mustang", 2022); $newCar = clone $myCar; $newCar->make = "Chevrolet"; $newCar->model = "Corvette"; echo "Original Car: " . $myCar->make . " " . $myCar->model . " " . $myCar->year . PHP_EOL; echo "New Car: " . $newCar->make . " " . $newCar->model . " " . $newCar->year . PHP_EOL; // Output: // Original Car: Ford Mustang 2022 // New Car: Chevrolet Corvette // Example 2 $myArray = [1, 2, 3]; $newArray = $myArray; $newArray[0] = 4; echo "Original Array: " . implode(", ", $myArray) . PHP_EOL; echo "New Array: " . implode(", ", $newArray) . PHP_EOL; // Output: // Original Array: 1, 2, 3 // New Array: 4, 2, 3
Result:
Report an issue