Classes & Objects
PHPObject-Oriented Programming (OOP) organizes code into reusable "objects" that contain both data (properties) and behavior (methods). It's the foundation of Laravel.
Creating a Class
PHP
<?php
class Car {
// Properties (data)
public string $brand;
public string $color;
public int $year;
// Method (behavior)
public function describe(): string {
return "{$this->year} {$this->brand} in {$this->color}";
}
public function honk(): void {
echo "Beep beep!";
}
}
?>Creating Objects (Instances)
PHP
<?php
// Create objects from the class
$car1 = new Car();
$car1->brand = "Toyota";
$car1->color = "red";
$car1->year = 2022;
$car2 = new Car();
$car2->brand = "Honda";
$car2->color = "blue";
$car2->year = 2023;
echo $car1->describe(); // 2022 Toyota in red
echo $car2->describe(); // 2023 Honda in blue
$car1->honk(); // Beep beep!
?>Access Modifiers
| Modifier | Accessible From |
|---|---|
public | Anywhere |
protected | Class + child classes |
private | Only within the class |
PHP
<?php
class BankAccount {
public string $owner;
private float $balance; // hidden from outside
public function deposit(float $amount): void {
$this->balance += $amount;
}
public function getBalance(): float {
return $this->balance; // controlled access
}
}
$account = new BankAccount();
$account->owner = "John";
$account->deposit(1000);
echo $account->getBalance(); // 1000
// $account->balance = 99999; // Error! balance is private
?>Static Properties & Methods
PHP
<?php
class Counter {
public static int $count = 0;
public static function increment(): void {
self::$count++;
}
}
Counter::increment();
Counter::increment();
echo Counter::$count; // 2 — shared across all instances
?>💡
Laravel uses classes everywhere! Controllers, Models, Middleware — they're all classes. Understanding OOP is essential for Laravel development.
Test your knowledge!
Take a quiz to reinforce what you learned.