AnyCompiler

Interfaces Aur Traits

PHP classes sirf ek hi parent ko extend kar sakti hain, lekin ek class kitne bhi interfaces implement kar sakti hai, aur kitne bhi traits istemal kar sakti hai — single inheritance se zyada chahne ke PHP ke do alag jawab. Ek interface method signatures declare karta hai bilkul baghair kisi body ke — ek pure contract, ek waada ke "jo bhi class mujhe implement karti hai us ke paas ye methods hain" — aur ek class jitne chahiye utne interfaces implement kar sakti hai, comma-separated. Trait is ke mukhalif hai: ye real method bodies hain, ek baar likhi gayi aur use TraitName se kisi bhi class mein mix ki gayi — ek shared base class ke baghair otherwise-unrelated classes ke darmiyan asal implementation share karne ka PHP ka tareeka.

<?php
interface Shape {
    public function area(): float;
}

trait Describable {
    public function describe(): string {
        return "This shape has area " . $this->area();
    }
}

class Circle implements Shape {
    use Describable;

    private float $radius;

    public function __construct(float $radius) {
        $this->radius = $radius;
    }

    public function area(): float {
        return M_PI * $this->radius ** 2;
    }
}

$c = new Circle(2);
echo round($c->area(), 2), "\n";
echo $c->describe(), "\n";
var_dump($c instanceof Shape);
Output
12.57
This shape has area 12.566370614359
bool(true)

Circle implements Shape, isi liye PHP enforce karta hai ke ye waqai area() ko matching signature ke sath define kare — $c instanceof Shape confirm karta hai ke wo contract qaim raha. use Describable ne ek mukammal taur par kaam karta describe() method pull kar liya baghair Circle ke andar bilkul koi code likhe; describe() $this->area() call karta hai, aur kyunke runtime par $this ek Circle hai, wo Circle ka khud ka area() call karta hai — ek trait ke methods us class ke context mein chalte hain jo bhi unhe mix karti hai. Next: working with strings and arrays together — array_map() aur array_filter() comprehensions ke PHP ke jawab ki tarah, real text processing par apply kiye gaye.

Practice exercise

Ek Greeter interface likho jis mein greet(): string ho, ek Loud trait jis mein ek shout() method ho jo strtoupper($this->greet()) return kare, aur ek Robot class jo Greeter implement kare aur Loud istemal kare, jahan greet() "beep boop" return kare — phir echo (new Robot())->shout() karo.