Object Cloning

PHP Programming

PHP Programming Examples

<?php
	class employee {
		private $employeeName;
		private $salary;

		function setEmployeeName($employee) {
			$this->employeeName = $employee;
		}

		function getEmployeeName() {
			return $this->employeeName;
		}

		function setSalary($salary) {
			$this->salary = $salary;
		}

		function getSalary() {
			return $this->salary;
		}
      
		/* __clone() method which is call by clone object */
		function __clone() {
			$this->salary = 10000;
		}
	}

	$emp1 = new employee();
	$emp1->setEmployeeName("Robert");
	$emp1->setSalary(20000);
   
	/* Cloning object */
	$emp2 = clone $emp1;
	$emp2->setEmployeeName("Jonny");

	echo "Employee1 Name: ".$emp1->getEmployeeName()."<br />";
	echo "Employee1 Salary: ".$emp1->getSalary()."<br />";

	echo "Employee2 Name: ".$emp2->getEmployeeName()."<br />";
	echo "Employee2 Salary: ".$emp2->getSalary();
?>


          /****** Output ******/
          

Employee1 Name: Robert


Employee1 Salary: 20000


Employee2 Name: Jonny


Employee2 Salary: 10000

Learn more about object cloning