PHP Access Modifiers

In PHP, access modifiers are keywords used to control the visibility and accessibility of properties and methods within a class. There are three main access modifiers in PHP:

There are three access modifiers:

  • public
  • protected
  • private

Public:

When a property or method is declared as public, it can be accessed from anywhere, both within the class itself and from outside the class.

class MyClass {
    public $publicProperty;

    public function publicMethod() {
        // Code here
    }
}

$obj = new MyClass();
$obj->publicProperty = 'Hello';
$obj->publicMethod();

In the example above, the $publicProperty property and the publicMethod() method are declared as public. They can be accessed and used from outside the class by creating an instance of the class.

Protected:

When a property or method is declared as protected, it can only be accessed within the class itself and by its subclasses (derived classes).

class MyClass {
    protected $protectedProperty;

    protected function protectedMethod() {
        // Code here
    }
}

class MySubClass extends MyClass {
    public function accessProtected() {
        $this->protectedProperty = 'Hello';
        $this->protectedMethod();
    }
}

$obj = new MySubClass();
$obj->accessProtected();

In the example above, the $protectedProperty property and the protectedMethod() method are declared as protected. They can be accessed within the class MyClass and its subclass MySubClass, but not from outside those classes.

Private:

When a property or method is declared as private, it can only be accessed within the class itself. It is not accessible from outside the class or by its subclasses.

class MyClass {
    private $privateProperty;

    private function privateMethod() {
        // Code here
    }
}

$obj = new MyClass();
$obj->privateProperty = 'Hello'; // Error: private property cannot be accessed
$obj->privateMethod(); // Error: private method cannot be accessed

In the example above, the $privateProperty property and the privateMethod() method are declared as private. They can only be accessed within the class MyClass itself.

By using access modifiers, you can enforce encapsulation and control the visibility of class members, ensuring that they are accessed and modified in a controlled manner.