PHP TUTORIALPHP TutorialPHP InstallationPHP Hello WorldPHP Basic SyntaxPHP CommentsPHP VariablesPHP Variable ScopePHP ConstantsPHP StringsPHP OutputPHP Data TypesPHP Type CastingPHP OperatorsPHP ConditionalsPHP Shorthand ConditionalsPHP LoopsPHP Loop Control StructuresPHP FunctionsPHP String FunctionsPHP ArraysPHP Superglobal VariablesPHP in HTMLPHP RegexRegex IntroductionRegex PCRE SyntaxPHP PREG FunctionsPHP FormsPHP Forms IntroductionPHP Forms CreatingPHP Forms SecurityPHP Forms ValidationPHP Forms Required InputsPHP Forms StickyPHP Forms Advanced ValidationPHP Forms FinishingPHP OOPPHP Object Oriented ProgrammingPHP OOP ClassesPHP OOP PropertiesPHP OOP ObjectsPHP OOP MethodsPHP OOP $this KeywordPHP OOP Constructors and DestructorsPHP OOP VisibilityPHP OOP InheritancePHP OOP Abstract Classes and MethodsPHP OOP Interfaces

PHP OOP Inheritance

The Concept of Inheritance

In Object-Oriented Programming, when a class derives from another class, it is called inheritance.

The derived class is the child, and the other class which the child derived from is the parent class. (Sometimes they are called sub class and super class respectively)

In another way, the child class extends the parent class.

PHP OOP Inheritance
PHP OOP Inheritance

The child class inherits all the public and protected properties and methods from the parent class. Additionally, it can have its own properties and methods.

Note: A child class can also be inherited by another class.

The later-explained concepts like abstraction and interfaces are based on inheritance.

In PHP, the extends keyword is used to declare an inherited class. See the example.

Inheriting Example

As in the above image, dog and cat are animals. They have common behaviors all the animals have, and also their own behaviors.

Let's create Person class as the parent and Tom class as the child. (You know Tom is a person)

class Tom extends Person {...} is the syntax for the child class.

PHP Inheritance Example


<?php
class Person {
	public $name;
	public $age;
	public function __construct($name, $age) {
		$this -> name = $name;
		$this -> age = $age;
	}
	public function introduce() {
		echo "My name is {$this -> name}. My age is {$this -> age}";
	}
}
/* Tom is inherited from Person */
class Tom extends Person {
	# __construct() is inherited
	# introduce() is inherited
	public function sayHello() {
		echo "Hello, World <br>";
	}
}
$tom = new Tom('Tom', 29);
$tom -> sayHello();
$tom -> introduce();

Run Example ››

Note these things in the example

Using Protected Visibility

We discussed the public and private visibility with several examples in the visibility chapter, but protected visibility was not fully described.

The main usage of protected is in inheritance. Protected variables are only available in:

By declaring a property or method protected, you can restrict it to the above-mentioned two classes.

PHP Protected Visibility for Inheritance


<?php
class ParentClass {
	protected $protectedProperty = 'Protected';
	private $privateProperty = 'Private';
	protected function protectedMethod() {
		echo $this -> protectedProperty;
	}
	private function privateMethod() {
		// cannot call this function 
		// from Child
	}
}
class Child extends ParentClass {
	public function doSomething() {
		$this -> protectedMethod();
		// invalid
		// $this -> privateMethod();
	}
}
$child = new Child();
$child -> doSomething();

// all of following are invalid (only public visibility is accessible from outside)
// echo $child -> protectedProperty;
// echo $child -> privateProperty;
// $child -> protectedMethod();
// $child -> privateMethod();

Run Example ››

Overriding Inherited Methods

The inherited methods can be overridden by redefining the method with the same name.

PHP Overriding Inherited Methods


<?php
class Person {
	public $name;
	public $age;
	public function __construct($name, $age) {
		$this -> name = $name;
		$this -> age = $age;
	}
	public function introduce() {
		echo "My name is {$this -> name}. My age is {$this -> age}";
	}
}
class Tom extends Person {
	public $school;
	// overriden method
	public function __construct($name, $age, $school) {
		$this -> name = $name;
		$this -> age = $age;
		$this -> school = $school;
	}
	public function introduce() {
		echo "My name is {$this -> name}. My age is {$this -> age}. My school is {$this -> school}";
	}
}
$tom = new Tom('Tom', 29, 'Foothill School');
$tom -> introduce();

Run Example ››

In the above example, we have overridden the __construct() and introduce() methods.

Calling the Parent's Methods

From the child class, we can call parent's methods using the parent keyword and :: (Scope Resolution Operator).

The Scope Resolution Operator is a special syntax in PHP which is used in some cases of OOP. We will see it more in the upcoming chapters.

Let's make a little change to our code. Here we will call the parent's constructor method from the child class.


parent::__construct();

Here's the updated code.

PHP Calling Parent's Methods


<?php
class Person {
	public $name;
	public $age;
	public function __construct($name, $age) {
		$this -> name = $name;
		$this -> age = $age;
	}
	public function introduce() {
		echo "My name is {$this -> name}. My age is {$this -> age}";
	}
}
class Tom extends Person {
	public $school;
	public function __construct($name, $age, $school) {
		# $this -> name and $this -> age will be set by the parent's constructor
		parent::__construct($name, $age);
		$this -> school = $school;
	}
	public function introduce() {
		echo "My name is {$this -> name}. My age is {$this -> age}. My school is {$this -> school}";
	}
}
$tom = new Tom('Tom', 29, 'Foothill School');
$tom -> introduce();

			

Run Example ››

When you override parent's methods, you cannot use $this -> methodName to refer to the parent's method as it now refers to the method of the child class. So, parent::methodName can be used.

Using the Final Keyword

There are two uses of the final keyword.

1. Preventing Class Inheritance


final class NonParent {
	// class code
}
// will throw an error
class Child extends NonParent {...}

2. Preventing Method Overriding


class ParentClass {
	final public function myMethod() {

	}
}
class Child extends ParentClass {
	// Fatal Error: Overriding final methods
	public function myMethod() {

	}
}

Why Inheritance?

Inheritance is an extremely useful concept in Object-Oriented Programming which allows us to prevent code duplication and manage big tasks easily.

In the next chapters, we will learn how to use this in real-world examples.

Facebook Twitter