The previous lesson built a class by hand, property by property. This one covers the three features that make classes genuinely powerful in practice.
A constructor — a special method named __construct() — runs automatically the moment an object is created, so you never have to set every property manually afterward:
<?php
class Student {
public $name;
public $course;
public function __construct($name, $course) {
$this->name = $name;
$this->course = $course;
}
}
$student = new Student("Priya", "Web Development"); // set in one line
?>| Keyword | Accessible from |
|---|---|
| public | Anywhere — inside the class, and from outside it |
| private | Only from inside this exact class |
| protected | This class, and any class that inherits from it |
<?php
class BankAccount {
private $balance = 0;
public function deposit($amount) {
$this->balance += $amount;
}
public function getBalance() {
return $this->balance;
}
}
$account = new BankAccount();
$account->deposit(500);
echo $account->getBalance(); // 500
// echo $account->balance; // Error — private, not accessible from outside
?>Why bother with private?
Making a property private and only exposing it through methods like getBalance() is called encapsulation — it stops outside code from setting $balance to an invalid value directly, since every change has to go through a method you control.
Inheritance lets one class build on another with extends, reusing its properties and methods instead of rewriting them:
<?php
class Person {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function greet() {
return "Hi, I'm {$this->name}.";
}
}
class Student extends Person {
public $course;
public function __construct($name, $course) {
parent::__construct($name); // reuse Person's constructor
$this->course = $course;
}
}
$s = new Student("Amit", "Graphic Design");
echo $s->greet(); // "Hi, I'm Amit." — inherited from Person, unchanged
?>parent:: calls a method from the class being extended — commonly used, as above, to reuse a parent's constructor instead of duplicating its logic.