Home Quizzes Leaderboard Competitions Learn Hire Us
About Contact
Log In Sign Up
Learn PHP Object-Oriented Programming --- Classes & Objects

Object-Oriented Programming --- Classes & Objects

⏱ 20 min read read
Key OOP Concepts:

class --- a blueprint that defines properties and methods

object --- an instance created from a class with new

property --- a variable that belongs to a class

\_\_construct --- constructor method, called on new ClassName()

method --- a function inside a class

$this --- refers to the current object (like Java's this)

Access Modifiers:

public --- accessible from anywhere

protected --- accessible from this class and subclasses

private --- accessible only from this class

Constructor Promotion (PHP 8.0+):

A powerful shorthand that declares and assigns properties in one step.

// Traditional way:

class Point {

public float $x;

public float $y;

public function \_\_construct(float $x, float $y) {

$this->x = $x;

$this->y = $y;

}

}

// Constructor promotion (PHP 8+):

class Point {

public function \_\_construct(

public float $x,

public float $y

) {} // That's it! Properties declared AND assigned.

}

Magic Methods:

\_\_construct() --- called on object creation

\_\_toString() --- called when object is converted to string (like
Python's \_\_str\_\_)

\_\_get() / \_\_set() --- property access interception

PHP uses $this->property (arrow ->) to access properties, NOT
$this.property

Public properties can be set directly: $obj->name = "Alice";

Use getters/setters or typed properties (PHP 7.4+) for validation.
Code Example
<?php

class BankAccount {

private float $balance;

// Constructor

public function \_\_construct(

public readonly string $owner, // PHP 8.1 readonly

float $initialBalance = 0

) {

$this->balance = $initialBalance;

}

// Getter

public function getBalance(): float {

return $this->balance;

}

// Controlled deposit

public function deposit(float $amount): void {

if ($amount > 0) {

$this->balance += $amount;

echo "Deposited $$amount. Balance: \${$this->balance}\n";

}

}

// Controlled withdrawal

public function withdraw(float $amount): bool {

if ($amount > $this->balance) {

echo "Insufficient funds!\n";

return false;

}

$this->balance -= $amount;

echo "Withdrew $$amount. Balance: \${$this->balance}\n";

return true;

}

// \_\_toString --- called by echo $obj

public function \_\_toString(): string {

return "Account[{$this->owner}, \${$this->balance}]";

}

}

// Create an object

$acc = new BankAccount("Alice", 1000.00);

$acc->deposit(500); // Deposited $500. Balance: $1500

$acc->withdraw(200); // Withdrew $200. Balance: $1300

$acc->withdraw(5000); // Insufficient funds!

echo $acc . "\n"; // Account[Alice, $1300]

echo $acc->owner . "\n"; // Alice

echo $acc->getBalance() . "\n"; // 1300

?>
← Functions Inheritance & Interfaces →

Log in to track your progress and earn badges as you complete lessons.

Log In to Track Progress