Access modifiers are keywords used in object-oriented programming languages to define the scope of a class member. In PHP, there are three access modifiers: public, protected, and private. These access modifiers determine how a class member can be accessed from outside the class.
The public access modifier allows a class member to be accessed from anywhere, both inside and outside the class. This means that any code can access the public member, regardless of where it is located.
The protected access modifier allows a class member to be accessed only from within the class or its subclasses. This means that any code outside the class or its subclasses cannot access the protected member.
The private access modifier allows a class member to be accessed only from within the class. This means that any code outside the class cannot access the private member.
Let's take a look at some code examples to better understand how access modifiers work in PHP.
class Person {
public $name;
public function sayHello() {
echo "Hello, my name is " . $this->name;
}
}
$person = new Person();
$person->name = "John";
$person->sayHello(); // Output: Hello, my name is John
In this example, the name
property and sayHello()
method are both declared as public. This means that they can be accessed from anywhere, both inside and outside the class. We create a new instance of the Person
class, set the name
property to "John", and call the sayHello()
method to output a greeting.
class Person {
protected $name;
protected function sayHello() {
echo "Hello, my name is " . $this->name;
}
}
class Employee extends Person {
public function introduce() {
$this->name = "Jane";
$this->sayHello(); // Output: Hello, my name is Jane
}
}
$employee = new Employee();
$employee->introduce();
In this example, the name
property and sayHello()
method are both declared as protected. This means that they can only be accessed from within the Person
class or its subclasses. We create a new subclass called Employee
that extends the Person
class. The introduce()
method sets the name
property to "Jane" and calls the sayHello()
method to output a greeting.
class Person {
private $name;
private function sayHello() {
echo "Hello, my name is " . $this->name;
}
public function introduce() {
$this->name = "John";
$this->sayHello(); // Output: Hello, my name is John
}
}
$person = new Person();
$person->introduce();
In this example, the name
property and sayHello()
method are both declared as private. This means that they can only be accessed from within the Person
class. We create a new instance of the Person
class and call the introduce()
method, which sets the name
property to "John" and calls the sayHello()
method to output a greeting.