Constructors and Visibility (public, private, protected)
Write safer classes using encapsulation and understand why private/protected matter in real apps.
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.