Classes aur Objects
class Dog { ... } ek class define karta hai; new Dog("Rex") uska ek instance banata hai. __construct() PHP ka constructor hai — exact wahi reserved naam wala ek method, jo automatically call hota hai jab new chalta hai. Kisi bhi method ke andar, $this current instance ko refer karta hai, aur -> (dot kabhi nahi) hai jaise aap kisi object par property reach karte ho ya method call karte ho: $this->name, $d->bark().
<?php
class Dog {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function bark() {
return "$this->name says Woof!";
}
}
$d = new Dog("Rex");
echo $d->bark(), "\n";
echo $d->name, "\n";
Rex says Woof! Rex
new Dog("Rex") ne __construct("Rex") call kiya, jisne "Rex" ko $this->name par store kar diya. Notice karo "$this->name says Woof!" ne $this->name ko directly ek double-quoted string ke andar interpolate kar diya, is simple property-access case ke liye koi extra braces chahiye nahi — strings lesson wala wahi interpolation rule, object properties tak extended. Next: visibility and encapsulation — public, private, protected, aur kyun zyada tar real PHP classes raw public properties ke bajaye getters expose karti hain.
Practice exercise
Ek Car class likho jiske paas public $brand property ho, ek constructor jo use set kare, aur ek drive() method jo "$brand is driving." return kare — phir echo (new Car("Toyota"))->drive() karo.