Inheritance (extends)

Inheritance is an Object Oriented concept that establishes a relationship between a Parent (/Super) class and a Child (/Sub) class.

 

The child is said to inherit the members of the parent.

 

The keyword extends is used in the class signature, as can be seen on line 8 as follows:

<?php
class Person {
	public $name ;
	public function speak() {
		echo "Hi, my name is $this->name, and I'm a person";
	}
}
class Scientist extends Person {
	public $hair ;
	public function speak() {
		echo "Hi, my name is $this->name, and I'm a Scientist!";
		echo "I also have long $this->hair hair!!";
	}
}
$julia = new Scientist ;
$julia->name = "Julia" ;
$julia->hair = "blonde" ;
$julia->speak() ;
?>

Save and refresh browser:

Hi, my name is Julia, and I'm a Scientist!
I also have long blonde hair!!

 

The new Scientist class has extended the Person class, and in this case has also overridden the speak() method of the parent.

Leave a Reply