php |tut

PHP OOP Inheritance

bazeng

Samuel K.M

Posted on October 28, 2021

PHP OOP Inheritance

Inheritance

Inheritance is when a class derives from another class.

Except for private properties & methods the child class will inherit all public and protected properties and methods from the parent class. In addition, it can have its own properties and methods.

An inherited class is defined by using the extends keyword.

<?php
class Person{ 
 //properties of the class

 public $name;
 public $age;
 public $gender;

 //methods of the class
 public function __construct($name,$age,$gender){
   $this->name = $name;
   $this->age = $age;
   $this->gender = $gender;
 }
 public function personalDetails(){
   echo "My name is {$this->name}, i am {$this->age} old and i am a {$this->gender}";
 }
}

class Interview extends Person{
    public function askForDetails(){
       echo "What is your name, age and gender?";
    }
}

$answer = new Interview("Samuel",18,"Male");
$answer->askForDetails();
$answer->personalDetails();
?>

Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
bazeng
Samuel K.M

Posted on October 28, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related