PHPPHP17 min read

Constructors and Visibility (public, private, protected)

Write safer classes using encapsulation and understand why private/protected matter in real apps.

Madison Reed
December 21, 2025
0.0k0

Professional OOP code protects data using visibility.

Visibility explained

- public: accessible anywhere - private: accessible only inside the class - protected: accessible in class and child classes

Example: encapsulation

```php <?php class BankAccount { private float $balance = 0;

public function deposit(float $amount): void { if ($amount <= 0) return; $this->balance += $amount; }

public function getBalance(): float { return $this->balance; } }

$acc = new BankAccount(); $acc->deposit(100); echo $acc->getBalance(); ?> ```

Notice: balance cannot be changed directly, only through deposit.

Why this matters

Encapsulation prevents accidental bugs like negative balances.

> Next: Inheritance, extending classes properly.

#PHP#OOP#Intermediate