DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 967,611 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Samuel K.M
Samuel K.M

Posted on

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

Top comments (0)

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.