🔐 PHP Access Modifiers – Control Visibility with public, private, and protected

Learn how to use access modifiers in PHP OOP to control the visibility of class properties and methods for better security and encapsulation.


🧲 Introduction – What Are Access Modifiers in PHP?

Access modifiers (also called visibility keywords) define how accessible class properties and methods are from outside or within a class. PHP provides three main access levels:

  • public – Accessible from anywhere
  • private – Accessible only inside the class
  • protected – Accessible inside the class and by child classes

🎯 In this guide, you’ll learn:

  • The meaning and use of public, private, and protected
  • When to use each modifier
  • How visibility supports encapsulation
  • Real-world examples and best practices

🔓 1. Public – Accessible from Anywhere

class User {
    public $name = "Alice";

    public function sayHello() {
        echo "Hello, $this->name!";
    }
}

$user = new User();
echo $user->name; // ✅ Accessible
$user->sayHello(); // ✅ Accessible

➡️ public members can be accessed from anywhere, including outside the class.
➡️ Best for methods or properties you intentionally expose.


🔐 2. Private – Accessible Only Within the Class

class Account {
    private $balance = 1000;

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

$acc = new Account();
// echo $acc->balance; ❌ Error: Cannot access private property
echo $acc->getBalance(); // ✅ 1000

➡️ private members are only accessible within the class itself.
➡️ Ideal for sensitive data like passwords, tokens, or internal states.


🛡️ 3. Protected – Accessible Within Class and Subclasses

class Vehicle {
    protected $type = "car";
}

class Bike extends Vehicle {
    public function showType() {
        return $this->type;
    }
}

$b = new Bike();
echo $b->showType(); // ✅ car
// echo $b->type; ❌ Error: Cannot access protected property

➡️ protected members can be accessed by the class itself and any subclass.
➡️ Useful for extending functionality while keeping it hidden from the outside.


🧪 4. Method Visibility Example

class Logger {
    private function log($msg) {
        echo "[LOG]: $msg";
    }

    public function info($msg) {
        $this->log($msg); // ✅ Internal call is allowed
    }
}

$log = new Logger();
// $log->log("Test"); ❌ Error: Private method
$log->info("Test"); // ✅ [LOG]: Test

➡️ Apply visibility to methods just like properties.
➡️ Encapsulate behavior while exposing only safe methods externally.


🔁 5. Inheritance + Access Modifier Behavior

ModifierSame ClassSubclassOutside Class
public
protected
private

📘 Choose the visibility level based on how and where the member should be accessed.


🧠 Best Practices

  • ✅ Keep properties private or protected by default
  • ✅ Use public methods as controlled interfaces
  • ✅ Use getter and setter methods to interact with private data
  • ❌ Avoid making every property public
  • ✅ Encapsulate internal logic and expose only necessary APIs

📌 Summary – Recap & Next Steps

Access modifiers help you write secure and maintainable OOP code by controlling how data and behavior are accessed. They enforce encapsulation, a key pillar of object-oriented programming.

🔍 Key Takeaways:

  • public → access anywhere
  • private → only within the class
  • protected → within class + subclasses
  • Use visibility to encapsulate data and protect your class structure

⚙️ Real-World Use Cases:
Secure payment gateways, data APIs, ORM classes, user authentication, and library components.


❓ Frequently Asked Questions (FAQs)

❓ Can I access a private property in a subclass?
❌ No. Use protected instead if it needs to be shared with subclasses.

❓ Is it bad to make everything public?
✅ Yes. It breaks encapsulation and makes your code harder to maintain or secure.

❓ Can methods be private in PHP?
✅ Absolutely. You can apply access modifiers to both properties and methods.

❓ Should constructors be public or private?
✅ Typically public, unless using patterns like Singleton or Factory where you want to restrict instantiation.

❓ What happens if I omit a visibility modifier?
🔸 In PHP, it defaults to public for methods (but you should always declare it explicitly for clarity).


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

🔐 PHP Access Modifiers

Or Copy Link

CONTENTS
Scroll to Top