Interfaces aur Traits
PHP classes sirf ek parent ko extend kar sakti hain, lekin ek class kitne bhi interfaces implement kar sakti hai, aur kitne bhi traits use kar sakti hai — single inheritance se zyada chahne ke PHP ke do distinct jawab. Ek interface method signatures declare karta hai bilkul bina kisi body ke — ek pure contract, ek promise ki "jo bhi class mujhe implement karti hai uske paas ye methods hain" — aur ek class jitne chahiye utne interfaces implement kar sakti hai, comma-separated. Trait iske opposite 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 bina otherwise-unrelated classes ke beech actual 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);
12.57 This shape has area 12.566370614359 bool(true)
Circle implements Shape, isliye PHP enforce karta hai ki ye really area() ko matching signature ke saath define kare — $c instanceof Shape confirm karta hai ki wo contract held raha. use Describable ne ek fully working describe() method pull kar liya bina Circle ke andar bilkul koi code likhe; describe() $this->area() call karta hai, aur kyunki 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 jisme greet(): string ho, ek Loud trait jisme ek shout() method ho jo strtoupper($this->greet()) return kare, aur ek Robot class jo Greeter implement kare aur Loud use kare, jahan greet() "beep boop" return kare — phir echo (new Robot())->shout() karo.