Prev | Current Page 266 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"

An assistant must be able to take a memo, and an office manager
needs to take supply inventories. Despite these differences, it would be quite inefficient
if you had to create and maintain redundant class structures for those attributes
that all classes share. The OOP development paradigm takes this into account, allowing
you to inherit from and build upon existing classes.
CHAPTER 7 ?–  ADVANCED OOP FEATURES 199
Class Inheritance
As applied to PHP, class inheritance is accomplished by using the extends keyword.
Listing 7-3 demonstrates this ability, first creating an Employee class and then creating
an Executive class that inherits from Employee.
?– Note A class that inherits from another class is known as a child class, or a subclass. The class from
which the child class inherits is known as the parent, or base class.
Listing 7-3. Inheriting from a Base Class
// Define a base Employee class
class Employee {
private $name;
// Define a setter for the private $name member.
function setName($name) {
if ($name == "") echo "Name cannot be blank!";
else $this->name = $name;
}
// Define a getter for the private $name member
function getName() {
return "My name is ".$this->name."
";
}
} // end Employee class
// Define an Executive class that inherits from Employee
class Executive extends Employee {
// Define a method unique to Employee
function pillageCompany() {
echo "I'm selling company assets to finance my yacht!";
}
200 CHAPTER 7 ?–  ADVANCED OOP FEATURES
} // end Executive class
// Create a new Executive object
$exec = new Executive();
// Call the setName() method, defined in the Employee class
$exec->setName("Richard");
// Call the getName() method
echo $exec->getName();
// Call the pillageCompany() method
$exec->pillageCompany();
?>
This returns the following:
My name is Richard.


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