Set your Publisher ID in src/config/ads.ts to display live ads.
Object-Oriented PHP: Classes, Inheritance & Encapsulation
Building modular enterprise systems with modern PHP OOP principles
PHP features a comprehensive Object-Oriented model complete with visibility modifiers, constructors, destructors, inheritance, interfaces, abstract classes, and traits.
Classes, Objects, and Access Modifiers
public: Properties and methods can be accessed from anywhere outside the class.
protected: Accessible only within the declaring class and its child classes (inheritance).
private: Accessible only within the specific class that defined it.
__construct(): Magic method invoked automatically when an object is instantiated with new.
<?php
class Account {
// PHP 8 Constructor Property Promotion with types
public function __construct(
private string $accountNumber,
private string $owner,
protected float $balance = 0.0
) {}
public function deposit(float $amount): void {
if ($amount <= 0) {
throw new InvalidArgumentException("Deposit must be positive.");
}
$this->balance += $amount;
}
public function getBalance(): float {
return $this->balance;
}
}
class SavingsAccount extends Account {
public function applyInterest(float $rate): void {
$interest = $this->balance * ($rate / 100);
$this->deposit($interest);
}
}
$mySavings = new SavingsAccount("ACC-9021", "David Miller", 1500.00);
$mySavings->deposit(500.00);
$mySavings->applyInterest(4.5);
echo "Current Balance: $" . $mySavings->getBalance();
?>Set your Publisher ID in src/config/ads.ts to display live ads.
Test Yourself With Exercise
Which visibility modifier restricts property access strictly to the declaring class itself?