PHP Classes and Objects
Object-oriented programming (OOP) groups data and the code that works on it into one unit called a class.
Class and Object
- A class is a plan or template, like the design of a car
- An object is a real thing made from that plan, like one actual car
- Properties are the data of an object (colour, model)
- Methods are functions inside a class (start, stop)
Your First Class
Example
<?php
class Student {
public string $name;
public int $marks;
public function result(): string {
return $this->marks >= 40 ? "Pass" : "Fail";
}
}
$s = new Student();
$s->name = "Ali";
$s->marks = 68;
echo $s->name . ": " . $s->result();Ali: Pass
new Student()creates an object->reaches a property or method of an object$thismeans "this object" inside the class
Constructors
A constructor runs automatically when you create the object. It is the place to set starting values.
Example
<?php
class Product {
public function __construct(
public string $name,
public float $price,
public int $stock = 0
) {}
public function label(): string {
return "{$this->name} - Rs " . number_format($this->price);
}
}
$fan = new Product("Ceiling Fan", 8500, 12);
echo $fan->label() . "<br>";
echo "In stock: " . $fan->stock;Ceiling Fan - Rs 8,500 In stock: 12
Writing public before the constructor parameters is called constructor promotion (PHP 8). It creates and fills the properties in one step.
Visibility
| Keyword | Who can use the property or method |
|---|---|
public | Everyone |
protected | The class and its child classes |
private | Only the class itself |
Keep data private and give methods to change it safely:
Example
<?php
class BankAccount {
private float $balance = 0;
public function deposit(float $amount): void {
if ($amount <= 0) {
throw new InvalidArgumentException("Amount must be positive.");
}
$this->balance += $amount;
}
public function getBalance(): float {
return $this->balance;
}
}
$acc = new BankAccount();
$acc->deposit(5000);
$acc->deposit(2500);
echo "Balance: Rs " . $acc->getBalance();Balance: Rs 7500
Writing $acc->balance = 1000000; from outside would give an error, because the property is private.
Inheritance
A child class gets everything from its parent class and can add or change things. Use extends:
Example
<?php
class Person {
public function __construct(protected string $name) {}
public function introduce(): string {
return "I am {$this->name}.";
}
}
class Teacher extends Person {
public function __construct(string $name, private string $subject) {
parent::__construct($name);
}
public function introduce(): string {
return parent::introduce() . " I teach {$this->subject}.";
}
}
$t = new Teacher("Sir Imran", "PHP");
echo $t->introduce();I am Sir Imran. I teach PHP.
Frameworks like Laravel and WordPress plugins use classes everywhere. Understanding OOP makes them much easier to learn.
Exercise
Exercise
Which keyword makes a property usable only inside its own class?
