🐶
PHP

PHP Public, Private, Protected Access Explained

By Filip on 10/21/2024

This article explains the differences between the public, private, and protected visibility keywords in PHP and how they affect the accessibility of class members.

PHP Public, Private, Protected Access Explained

Table of Contents

Introduction

In object-oriented programming with PHP, controlling access to the internal components of your classes is fundamental for building well-structured and maintainable applications. PHP provides visibility keywords to manage how properties (variables) and methods (functions) within a class can be accessed. These keywords are essential for implementing encapsulation, a core principle of OOP. This article will guide you through the three visibility keywords in PHP: public, private, and protected, explaining their usage and significance.

Step-by-Step Guide

In PHP, you control access to properties and methods within classes using visibility keywords: public, private, and protected.

1. Public:

  • Accessible from everywhere.
  • No restrictions.
class MyClass {
    public $name = "John"; 
}

$obj = new MyClass();
echo $obj->name; // Output: John

2. Private:

  • Accessible only within the class where they are defined.
  • Encapsulation: Helps prevent accidental modification from outside.
class MyClass {
    private $secret = "password123";

    public function getSecret() {
        return $this->secret; 
    }
}

$obj = new MyClass();
// echo $obj->secret; // Error: Cannot access private property
echo $obj->getSecret(); // Output: password123 

3. Protected:

  • Accessible within the class itself AND by classes that inherit from it (subclasses).
  • Strikes a balance between encapsulation and inheritance.
class ParentClass {
    protected $value = 10;
}

class ChildClass extends ParentClass {
    public function showValue() {
        echo $this->value; 
    }
}

$obj = new ChildClass();
$obj->showValue(); // Output: 10

Choosing the Right Visibility:

  • public: When you want to expose data or behavior directly.
  • private: For internal implementation details that shouldn't be modified externally.
  • protected: When you want to share data/behavior with subclasses while still restricting direct access from outside the class hierarchy.

Code Example

This PHP code demonstrates the concepts of public, private, and protected visibility in object-oriented programming. It defines three classes: MyClass with a public property and method, MyClassPrivate with a private property and methods to access it, and ParentClass with protected members that are accessed by its subclass ChildClass. The code showcases how each visibility level restricts access to class members from different scopes, highlighting the principles of encapsulation and inheritance.

<?php

// 1. Public Visibility
class MyClass {
    public $name = "John"; 

    public function greet() {
        echo "Hello, my name is " . $this->name;
    }
}

$obj = new MyClass();
echo $obj->name . "<br>"; // Accessing public property
$obj->greet(); // Accessing public method
echo "<br>";

// 2. Private Visibility
class MyClassPrivate {
    private $secret = "password123";

    public function getSecret() {
        return $this->secret; 
    }

    private function aPrivateMethod() {
        echo "This is a private method.";
    }
}

$objPrivate = new MyClassPrivate();
// echo $objPrivate->secret; // Error: Cannot access private property
// $objPrivate->aPrivateMethod(); // Error: Cannot access private method
echo $objPrivate->getSecret(); // Accessing private property via public method
echo "<br>";

// 3. Protected Visibility
class ParentClass {
    protected $value = 10;

    protected function protectedMethod() {
        echo "This is a protected method.";
    }
}

class ChildClass extends ParentClass {
    public function showValue() {
        echo $this->value . "<br>"; // Accessing protected property from parent
        $this->protectedMethod(); // Accessing protected method from parent
    }
}

$objChild = new ChildClass();
$objChild->showValue(); 
// echo $objChild->value; // Error: Cannot access protected property directly

?>

Explanation:

  • Public: The name property and greet() method in MyClass are accessible from anywhere.
  • Private: The secret property and aPrivateMethod() method in MyClassPrivate are only accessible within that class itself. We use the getSecret() method to provide controlled access to the private secret.
  • Protected: The value property and protectedMethod() method in ParentClass are accessible within the class and its subclass ChildClass. The ChildClass can use and modify these protected members.

This example demonstrates how visibility keywords control access to class members and help you enforce encapsulation and structure your code effectively.

Additional Notes

General:

  • Default Visibility: If no visibility keyword is specified, the member (property or method) is considered public. However, it's best practice to always explicitly define visibility for clarity.
  • Visibility and Inheritance: A subclass inherits all members from its parent class, except for private members. Protected members are inherited and can be accessed within the subclass.
  • Getters and Setters: Private properties are often accessed and modified indirectly using public "getter" and "setter" methods. This allows for controlled access and data validation.

Beyond the Basics:

  • Interfaces and Abstract Classes: Visibility plays a role in defining interfaces (all methods must be public) and abstract classes (can have protected and abstract methods).
  • Reflection: PHP's Reflection API allows you to inspect and manipulate classes, including their visibility modifiers, at runtime. This is an advanced topic used in frameworks and debugging tools.

Best Practices:

  • Favor Private and Protected: Start with the most restrictive visibility (private) and only make members public if absolutely necessary. This promotes encapsulation and reduces the risk of unintended side effects.
  • Document Clearly: Always document the intended visibility of your class members using PHPDoc comments. This helps other developers (and your future self) understand how your code is designed to be used.

Real-World Analogy:

Think of a house:

  • Public: The front door, anyone can access it.
  • Private: Your bedroom, only accessible by you.
  • Protected: The kitchen, accessible by family members (subclasses).

Summary

Keyword Access Level Description Encapsulation Inheritance
public Everywhere No restrictions, accessible from anywhere. Least N/A
private Class Only Accessible only within the defining class. Most Not inherited
protected Class & Subclasses Accessible within the class and its subclasses. Balanced Inherited

Choosing the Right Visibility:

  • public: For exposing data and behavior directly.
  • private: For internal implementation details, preventing external modification.
  • protected: For sharing data/behavior with subclasses while restricting external access.

Conclusion

Mastering visibility keywords is crucial for writing well-encapsulated, maintainable, and robust object-oriented code in PHP. By understanding and appropriately using public, private, and protected, you ensure that your classes' internal workings are protected while providing controlled access to the necessary data and functionality. This approach leads to more modular, reusable, and easier-to-maintain code, which are hallmarks of well-designed software.

References

Were You Able to Follow the Instructions?

😍Love it!
😊Yes
😐Meh-gical
😞No
🤮Clickbait