Besides encapsulation, another major advantage of object-oriented code is reuse. Reusing code reduces development time and the number of bugs. Object-oriented programming promotes reuse through a process known an inheritance.

Extending Classes

With inheritance, you can modify a class by adding or rewriting its methods. This allows your new class to be more specific than the original one, while still allowing you access to all the methods of the first class. The original class is known as the parent, and the new class is called the child.

Creating a child class is also called extending a class or subclassing an object. The original class that’s extended can also be called a super class or a base class.

For instance, you can extend Person to create an Employee class, where an Employee is a Person with a salary.

When extending a class, abide by the “is a” rule. You should always be able to say, “Child class is a Parent class.” Following this rule leads to clean relationships between your classes. This example is okay because an Employee is a Person:

class Person { private $name; public function setName($name) { $this->name = $name; } public function getName( ) { return $this->name; } } class Employee extends Person { private $salary; public function setSalary($salary) { $this->salary = $salary; } public function getSalary( ) { return $this->salary; } } $billg = new Employee; $billg->setName('Bill Gates'); $billg->setSalary(865114); // Actual 2003 salary ...

Get Upgrading to PHP 5 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.