DEV Community

AI_Dosage
AI_Dosage

Posted on

3 1

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

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more