AnyCompiler

Classes Aur Objects

class Dog { ... } ek class define karta hai; new Dog("Rex") us ka ek instance banata hai. __construct() PHP ka constructor hai — ain wahi reserved naam wala ek method, jo khud ba khud call hota hai jab new chalta hai. Kisi bhi method ke andar, $this current instance ko refer karta hai, aur -> (dot kabhi nahi) hai jis se aap kisi object par property tak pohonchte 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";
Output
Rex says Woof!
Rex

new Dog("Rex") ne __construct("Rex") call kiya, jis ne "Rex" ko $this->name par store kar diya. Dekho "$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 nahi chahiye — strings lesson wala wohi interpolation rule, object properties tak phaila hua. Next: visibility and encapsulation — public, private, protected, aur kyunke aksar real PHP classes raw public properties ke bajaye getters expose karti hain.

Practice exercise

Ek Car class likho jis ke paas public $brand property ho, ek constructor jo isay set kare, aur ek drive() method jo "$brand is driving." return kare — phir echo (new Car("Toyota"))->drive() karo.