Lesson 21 of 32Article19 min
OOP — Access Modifiers, Inheritance & Constants
public — accessible everywhere. protected — class + child classes. private — only inside the same class.
Access Modifiers
public — accessible everywhere. protected — class + child classes. private — only inside the same class.
Real-life example: public is a shop window. protected is staff-only back room. private is the owner's safe.
public, protected, private
<?php
class Account {
public string $username = "asha";
protected float $balance = 1000.0;
private string $pin = "1234";
}
$acc = new Account();
echo $acc->username;
// echo $acc->balance; // Error — protected
?>Inheritance
A child class extends a parent with extends ParentClass. It inherits methods and can override them.
Real-life example: Inheritance is a family recipe — the child adds new spices but keeps the base dish.
extends and override
<?php
class Animal {
public function speak(): string {
return "Some sound";
}
}
class Dog extends Animal {
public function speak(): string {
return "Woof!";
}
}
$dog = new Dog();
echo $dog->speak();
?>Class Constants
Define constants inside a class with const NAME = value. Access with ClassName::NAME or self::NAME inside the class.
Real-life example: Class constants are the company logo color — same everywhere, never changes per employee.
Class constant
<?php
class Config {
public const SITE_NAME = "Rishtaara";
public const MAX_UPLOAD_MB = 5;
}
echo Config::SITE_NAME;
echo Config::MAX_UPLOAD_MB . " MB max";
?>