AnyCompiler

Inheritance

class Cat extends Animal, Cat ko Animal ki har public aur protected property aur method khud ba khud de deta hai. Cat kisi bhi inherited method ko sirf same naam se redeclare kar ke override kar sakta hai — aur us override ke andar se, parent::methodName() parent class se original, bina-override version ko call karta hai, ek subclass ko behavior ko mukammal taur par replace karne ke bajaye extend karne deta hai.

<?php
class Animal {
    protected string $name;

    public function __construct(string $name) {
        $this->name = $name;
    }

    public function speak(): string {
        return "$this->name makes a sound.";
    }
}

class Cat extends Animal {
    public function speak(): string {
        return parent::speak() . " Actually, $this->name says Meow.";
    }
}

$c = new Cat("Whiskers");
echo $c->speak(), "\n";
Output
Whiskers makes a sound. Actually, Whiskers says Meow.

$c->speak() ne Cat ka override chalaya, jo khud parent::speak() ko call karta hai Animal ka original sentence lene ke liye apna append karne se pehle — dono sentences ek hi final string mein dikhte hain. $name private ke bajaye khaas taur par protected declare kiya gaya hai taake Cat (aur koi bhi doosri subclass) $this->name ko directly parh sake; agar ye private hota, to sirf Animal ke apne methods hi isay touch kar sakte. PHP sirf single inheritance support karta hai — ek class mein sirf ek hi extends — isi liye interfaces aur traits, next, is ke "mujhe ek se zyada parent chahiye" ke do alag jawab hain.

Practice exercise

Ek Vehicle class likho jis ke paas protected $name ho aur ek describe() method jo "$name is a vehicle." return kare, phir ek Car extends Vehicle jo describe() ko override kare parent::describe() plus " Specifically, a car." return karne ke liye — "Sedan" naam wali Car ke liye result echo karo.