Access Modifiers: Public vs Private
Explore how public and private access modifiers in PHP manage access to class properties and methods. Understand how to use getters and setters to safely interact with private properties, enhancing the security and encapsulation in your PHP object-oriented programs.
The public access modifier
The public access modifier allows code from both outside and inside the class to access the class’s methods and properties.
How to access a public property
In the following example, the class’s property and method are defined as public, so the code outside the class can directly interact with them.
In line 15, we set the public property $model outside the class. In line 18, we call the public method getModel() from outside the class.
The private access modifier
The private access modifier prevents access to a class’s methods or properties from any code outside the class. We can prevent access to the properties and methods inside our classes if we define them with the private access modifier instead of the public access modifier.
In the following example, we define the property $model as private. When we try to set its value from outside the class, we encounter a fatal error.
How to access private properties
We can see that we have no access to private properties from outside the class, but we still have to somehow set and get the properties values.
In order to interact with private properties, we use public methods because they can interact with both the code outside of the class’s scope and the code inside the class.
The public methods that can interact in this manner are commonly divided into two groups:
- Setters: These set the values of the private properties.
- Getters: These get the values of the private properties.
Example
In the following example, we will see that we can get and set the value of a private property $model through the use of setter and getter methods.
We will use the setModel() method to set the value of the car model and the getModel() method to get the value of the property.
In line 22, we set the private property $model using setter function setModel().
In line 25, we get the private property $model using the getter function getModel().