Introduction
So far a record such as a bank account needed several separate variables and several functions. Object-oriented programming, or OOP, puts data and the functions that use it together. A class is a plan for a kind of thing, and an object is one real thing made from that plan. A class BankAccount can have a balance and the actions deposit and withdraw, and every account is an object of that class with its own balance. OOP keeps code organised and protects data from wrong changes.
How it works
You define a class with class and create objects with new:
$a = new BankAccount("Ada", 100);
$a->deposit(50.5);
The arrow -> reaches a property or calls a method of an object. Inside the class, $this means "the object that is running this method".
The properties are the variables of the class, and the methods are its functions. A special method, __construct, runs when the object is created. PHP 8 has constructor promotion: writing private string $owner in the constructor's parameter list declares the property and fills it at once.
Visibility controls who can use a member. public means everyone, private only the class itself, and protected the class and its children. The good habit is to make properties private and give controlled access through public methods. This is called encapsulation. In withdraw, the class decides whether the balance is big enough, so no code outside can make the balance negative by mistake.
A constant belongs to the class: public const MIN_DEPOSIT = 1; and you read it with self::MIN_DEPOSIT. A static property or method belongs to the class and not to one object. self::$count++ counts all accounts, and BankAccount::accountsOpened() is called with the double colon, without an object.
The method __toString tells PHP how to turn an object into text, so echo $a works. Type declarations on properties and methods, such as float and bool, make errors clear.
Objects behave differently from arrays and numbers when you assign them. With $c = $a; both variables point to the same object, so a change through $c is visible through $a. To get an independent copy, use clone. You can ask $a instanceof BankAccount whether an object belongs to a class.
Example
<?php
class BankAccount
{
private float $balance;
private static int $count = 0;
public const MIN_DEPOSIT = 1;
public function __construct(private string $owner, float $start = 0)
{
$this->balance = $start;
self::$count++;
}
public function deposit(float $amount): void
{
if ($amount < self::MIN_DEPOSIT) {
return;
}
$this->balance += $amount;
}
public function withdraw(float $amount): bool
{
if ($amount > $this->balance) {
return false;
}
$this->balance -= $amount;
return true;
}
public function getBalance(): float
{
return $this->balance;
}
public function __toString(): string
{
return sprintf("%s: %.2f", $this->owner, $this->balance);
}
public static function accountsOpened(): int
{
return self::$count;
}
}
$a = new BankAccount("Ada", 100);
$b = new BankAccount("Bo");
$a->deposit(50.5);
$b->deposit(0.5);
echo $a, "\n";
echo $b, "\n";
echo $a->withdraw(500) ? "paid" : "refused", "\n";
echo $a->withdraw(20) ? "paid" : "refused", "\n";
echo $a->getBalance(), "\n";
echo BankAccount::accountsOpened(), "\n";
$c = $a;
$c->deposit(10);
echo $a->getBalance(), "\n";
$d = clone $a;
$d->deposit(100);
echo $a->getBalance(), " ", $d->getBalance(), "\n";
var_dump($a instanceof BankAccount);Line by line
- The class has a private balance, a static counter, a constant and a constructor with a promoted
$owner. depositandwithdrawprotect the balance by checking the rules.__toStringformats the account forecho.- Two objects are created, and a deposit is made to each.
- A withdrawal of 500 is refused, and one of 20 is paid.
- The static method reports that two accounts were opened.
$c = $ashares one object, so the deposit shows in$a.clonemakes a separate copy, so only$dchanges.
Expected result
Ada: 150.50
Bo: 0.00
refused
paid
130.5
2
140.5
140.5 240.5
bool(true)
In the real world
Almost every modern PHP project is object-oriented. Frameworks such as Laravel and Symfony are collections of classes, and a typical shop has classes for Product, Cart, Order and Customer. Keeping the rules inside the class that owns the data means a rule such as "a balance cannot be negative" is written in one place and works everywhere.
Common mistakes
- Forgetting
$this->when reading a property inside a method. - Making every property public, so any code can break the rules.
- Using
.instead of->to call a method. - Thinking that
$c = $acopies an object. It copies only the reference; useclone.
Best practices
- Keep properties private and offer small public methods.
- Give a class one clear responsibility.
- Use constructor promotion and type declarations.
- Name classes with a capital letter and methods with a verb.
Summary
A class describes the data and the actions of a thing, and new creates an object. Use -> to reach members and $this inside the class. The constructor sets up the object, visibility protects data, static and constant members belong to the class, and __toString turns an object into text. Assigning an object shares it; clone copies it.
Quick check
Key takeaways
- A class describes data and actions, and new makes an object.
- Private properties with public methods protect the data.
- Assigning an object shares it; clone makes a copy.
Practice problems for this lesson
Was this lesson clear?
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.