In PHP, access modifiers are an important part of object-oriented programming (OOP). They specify the scope of class variables or methods and how they can be accessed. In this post, we will look at the different types of access modifiers in PHP and offer examples of how to use them.
Access Modifier Types in PHP
In PHP, access modifiers are classified as public, private, or protected.
- Public: A method or attribute that is set to public can be accessed everywhere. This is the default access modifier in PHP.
- Private: A method or attribute that is set to private can only be accessed within the class in which it is created.
- Protected: A method or attribute that is set to protected can be accessed within the class in which it is created, as well as in classes that inherit from that class.
Example:
class Person{
public $name;
protected $age;
private $height;
}
$x= new Person();
$x->name = 'John'; // OK
$x->age= '32'; // ERROR
$x->height= '5.4'; // ERROR
Public, Private, and Protected Methods
class Person{
public $name;
public $age;
public $height;
function set_name($n) { // a public function (default)
$this->name = $n;
}
protected function set_age($a) { // a protected function
$this->age = $a;
}
private function set_height($h) { // a private function
$this->height = $h;
}
}
$person = new Person();
$person->set_name('John'); // OK
$person->set_age('26'); // ERROR
$person->set_height('5.4'); // ERROR