PHP - Access Modifiers

Access modifiers in PHP determine the visibility and accessibility of class members (properties and methods) from different scopes, like within the class, from derived classes, and from outside the class. There are three main access modifiers in PHP:

Public (public):

Public members can be accessed from anywhere, including outside the class.

They are accessible within the class, from derived classes, and from outside the class.

Example:

class MyClass {

    public $publicProperty;

    public function publicMethod() {

        // Code here

    }

}

$obj = new MyClass();
$obj->publicProperty = "Public Property"; // Accessible
$obj->publicMethod(); // Accessible

Protected (protected):

Protected members can be accessed within the class and from derived classes.

They are not directly accessible from outside the class hierarchy.

Example:

class MyClass {

    protected $protectedProperty;

    protected function protectedMethod() {

        // Code here

    }

}

class SubClass extends MyClass {

    public function accessProtected() {

        $this->protectedProperty = "Protected Property"; // Accessible

        $this->protectedMethod(); // Accessible

    }

}

Private (private):

Private members can only be accessed within the class that defines them.

They are not accessible from derived classes or from outside the class.

Example:

class MyClass {

    private $privateProperty;

    private function privateMethod() {

        // Code here

    }

}

$obj = new MyClass();
$obj->privateProperty = "Private Property"; // Not accessible (error)
$obj->privateMethod(); // Not accessible (error)

By using access modifiers, you can control the visibility and accessibility of your class members, which is crucial for encapsulation and data hiding. This helps ensure that the internal implementation details of your classes are hidden from external code and provides a clear API for interacting with your objects.