Access modifiers are used in object-oriented programming to control the visibility of properties and methods of a class from the outside world. In PHP OOP, there are three access modifiers:
- Public: A public property or method can be accessed from anywhere, both within the class and outside the class.
- Protected: A protected property or method can only be accessed from within the class and any child classes that inherit from the class.
- Private: A private property or method can only be accessed from within the class itself.
Here is an example of a class with public, protected, and private properties and methods:
class Person { public $name; //public property protected $age; //protected property private $email; //private property public function __construct($name, $age, $email) { $this->name = $name; $this->age = $age; $this->email = $email; } public function getAge() { //public method return $this->age; } protected function getEmail() { //protected method return $this->email; } private function setName($name) { //private method $this->name = $name; } }
In this example, the name
property is public, so it can be accessed from outside the class using object instances. The age
property is protected, so it can only be accessed from within the class and any child classes that inherit from it. The email
property is private, so it can only be accessed from within the class itself.
Similarly, the getAge()
method is public, so it can be called from outside the class using object instances. The getEmail()
method is protected, so it can only be called from within the class and any child classes that inherit from it. The setName()
method is private, so it can only be called from within the class itself.