PHP Syntax OOP Terms Inheritance

 

- Info:

- Ineritance allows classes to inherit fields and methods from one other class.

- Ingeritance is done by using keyword extends:

class Soldier extends Person

- Multiple inheritance is not supported in PHP.

 

- Single File:

- This example shows how class Soldier inherits field $name and method displayName() from class Person.

- Creat PHP Console Application Test.php.

 

Person.php

<?php

//CLASS PERSON.-------------------------------------------------------

class Person {

public $name = "John";

public function displayName() { echo $this->name; }

}

//CLASS SOLDIER.------------------------------------------------------

class Soldier extends Person {

public $weapon = "Rifle";

public function attack() { echo "Attack"; }

}

//USE CLASS.----------------------------------------------------------

$john = new Soldier(); //Create Object from Class.

$john->displayName();

?>