Prev | Current Page 263 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"

The example code instantiates a
Corporate_Drone object and uses it as the basis for demonstrating the effects of a
clone operation.
Listing 7-1. Cloning an Object with the clone Keyword
class Corporate_Drone {
private $employeeid;
private $tiecolor;
// Define a setter and getter for $employeeid
function setEmployeeID($employeeid) {
$this->employeeid = $employeeid;
}
function getEmployeeID() {
return $this->employeeid;
}
// Define a setter and getter for $tiecolor
function setTieColor($tiecolor) {
$this->tiecolor = $tiecolor;
}
function getTieColor() {
return $this->tiecolor;
}
}
// Create new Corporate_Drone object
$drone1 = new Corporate_Drone();
196 CHAPTER 7 ?–  ADVANCED OOP FEATURES
// Set the $drone1 employeeid member
$drone1->setEmployeeID("12345");
// Set the $drone1 tiecolor member
$drone1->setTieColor("red");
// Clone the $drone1 object
$drone2 = clone $drone1;
// Set the $drone2 employeeid member
$drone2->setEmployeeID("67890");
// Output the $drone1 and $drone2 employeeid members
printf("drone1 employeeID: %d
", $drone1->getEmployeeID());
printf("drone1 tie color: %s
", $drone1->getTieColor());
printf("drone2 employeeID: %d
", $drone2->getEmployeeID());
printf("drone2 tie color: %s
", $drone2->getTieColor());
?>
Executing this code returns the following output:
drone1 employeeID: 12345
drone1 tie color: red
drone2 employeeID: 67890
drone2 tie color: red
As you can see, $drone2 became an object of type Corporate_Drone and inherited
the member values of $drone1.


Pages:
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275