Understanding public, protected, and private Access Modifiers in PHP with Examples

Understand the difference between public, protected, and private in PHP. Learn how access modifiers control visibility in classes with real-world examples and best practices.

Understanding public, protected, and private Access Modifiers in PHP with Examples Image

When working with object-oriented programming (OOP) in PHP, you'll often encounter three important keywords: public, protected, and private. These are known as access modifiers. They define the visibility of class properties and methods, helping you control how your code is accessed and used.

In this blog post, we'll explore what these keywords mean, how they work, and when to use themβ€”with clear, real-world code examples.

πŸ”§ What Are Access Modifiers in PHP?

Access modifiers are used in class definitions to restrict or allow access to class members (properties and methods). PHP provides three access levels:

  • public: Accessible everywhere
  • protected: Accessible within the class and its child classes
  • private: Accessible only within the class itself

Let’s explore each of them in detail.

πŸ”“ public Keyword in PHP

The public modifier allows class members to be accessed from anywhereβ€”inside the class, outside the class, and in child classes.

βœ… Example:

class Demo {
    public $name = "Dinesh";
    public function greet() {
        return "Hello, " . $this->name;
    }
}
$obj = new Demo();
echo $obj->name;         // Output: Dinesh
echo $obj->greet();      // Output: Hello, Dinesh

πŸ“ Use Case:

Use public when you want properties or methods to be accessible to all parts of your code.

πŸ” private Keyword in PHP

The private modifier restricts access to class members only within the class where they are defined. They cannot be accessed outside the class or even from child classes.

❌ Direct Access Example (Error):

class Demo {
    private $name = "Dinesh";
}
$obj = new Demo();
echo $obj->name; // ❌ Error: Cannot access private property

βœ… Correct Usage with Getter Method:

class Demo {
    private $name = "Dinesh";
    public function getName() {
        return $this->name;
    }
}
$obj = new Demo();
echo $obj->getName(); // Output: Dinesh

πŸ“ Use Case:

Use private for sensitive data or helper methods that should not be exposed outside the class.

πŸ›‘οΈ protected Keyword in PHP

The protected modifier allows class members to be accessed within the same class and in any class that inherits from it, but not from outside.

❌ Direct Access Example (Error):

class Demo {
    protected $name = "Dinesh";
}
$obj = new Demo();
echo $obj->name; // ❌ Error: Cannot access protected property

βœ… Accessing from a Child Class:

class Demo {
    protected $name = "Dinesh";
    protected function greet() {
        return "Hello, " . $this->name;
    }
}
class ChildDemo extends Demo {
    public function getGreeting() {
        return $this->greet(); // Allowed: Accessing protected method from child class
    }
}
$obj = new ChildDemo();
echo $obj->getGreeting(); // Output: Hello, Dinesh

πŸ“ Use Case:

Use protected when you want to share functionality between a parent and its child classes, but not expose it publicly.

πŸ“Š Summary Table

ModifierSame ClassChild ClassOutside Class
publicβœ…βœ…βœ…
protectedβœ…βœ…βŒ
privateβœ…βŒβŒ

 πŸš€ When to Use Each Modifier?

Access ModifierBest Used For
publicWhen you want full access from anywhere
protectedWhen you want to restrict access to class hierarchy only
privateWhen data or logic should be completely internal to a class

βœ… Real-World Example

Let’s say you’re building a User class. You might want the name to be publicly readable, but the password should never be accessed or modified directly:

class User {
    public $username;
    private $password;

    public function __construct($username, $password) {
        $this->username = $username;
        $this->password = $password;
    }

    public function checkPassword($inputPassword) {
        return $this->password === $inputPassword;
    }
}

$user = new User("Dinesh", "secret123");
echo $user->username;          // βœ… Public access
// echo $user->password;       // ❌ Error: Private property
echo $user->checkPassword("secret123"); // βœ… True

🎯 Final Thoughts

Understanding the differences between public, protected, and private is essential for writing clean, secure, and maintainable PHP code. They give you the tools to encapsulate data, prevent accidental modification, and build reusable class hierarchies.

πŸ” Use public sparingly, protected strategically, and private thoughtfully.

Happy Coding! 😊

Tags

PHP

Do you Like?