public, protected, private) & EncapsulationAccess modifiers control the visibility and scope accessibility of class properties and methods from outside the class or from inherited child classes.
| Modifier | Access Inside Same Class | Access Inside Child Class (extends) |
Access Outside Class (Public API) |
|---|---|---|---|
public |
Yes | Yes | Yes |
protected |
Yes | Yes | No |
private |
Yes | No | No |
flowchart TD
A["Class Instance Object"] --> B["public: Accessible from anywhere"]
A --> C["protected: Accessible in class & derived child subclasses"]
A --> D["private: Enclosed strictly inside defining class scope"]
<?php
declare(strict_types=1);
class BankAccount
{
public string $accountHolder; // Public: Accessible anywhere
protected string $accountType; // Protected: Accessible in child classes
private float $balance; // Private: Accessible ONLY in BankAccount
public function __construct(string $holder, string $type, float $initialDeposit)
{
$this->accountHolder = $holder;
$this->accountType = $type;
$this->balance = max(0.0, $initialDeposit);
}
// Encapsulated getter for private property
public function getBalance(): float
{
return $this->balance;
}
// Encapsulated method with validation controls
public function deposit(float $amount): void
{
if ($amount > 0) {
$this->balance += $amount;
}
}
}
class SavingsAccount extends BankAccount
{
public function getAccountDetails(): string
{
// Can access $this->accountType (protected), but NOT $this->balance (private)!
return "Holder: {$this->accountHolder} | Type: {$this->accountType} | Balance: $" . $this->getBalance();
}
}
$account = new SavingsAccount("Maksudur", "High-Yield Savings", 1500.00);
echo $account->getAccountDetails() . "
";
// Attempting to access $account->balance directly throws a Fatal Uncaught Error!
private or protected Properties: Protect internal state from direct external modification.public getter and setter methods that validate state changes.protected for Extendable Base Classes: Use protected if you anticipate child subclasses extending and referencing internal properties.Which access modifier allows property access inside the defining class and its subclasses, but forbids external access? (protected)
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.