Extending Classes

PHP allows you to define classes that extend the functionality of an existing class. The new class will have access to all of the protected and public properties and methods of its parent class from within the class definition itself and all of the public properties and methods of the parent class can be accessed as if they are properties and methods of the newly extended child class.

class BaseClass {
protected $var = 'a default value';
public function displayVar() {
echo $this->var;
class SubClass extends BaseClass {
public function setVar($v) {
$this->var = $v;

In this example our base class defines a protected property and a method for displaying it. If we instantiate an object of this class then we have a read only value since the class defines a way to read the value in the property but no way of updating it. In so far as trying to reference the $var property of the BaseClass from objects instantiated from this class is concerned the property is private and cannot be accessed from anywhere other than the method defined for the class.

We extend the functionality of this class we use the extends keyword in defining a new SubClass. This new class now not only has the setVar method defined in its declaration but it also inherits the displayVar method and $var property from BaseClass. In this case $var is inherited because it is defined as protected. Were it defined as private then it would not be inherited and our attempt to update its value would not work. Because it is defined as protected it is still only able to be accessed from within the class.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow