Introduction
The access modifier is the most important feature of the OO language and it is used to restrict the function and classes to be accessed. The list of the access modifiers are:
- Public
Class properties and methods, that are set to be public, can be accessed anywhere in the PHP script, in other words everywhere.
- Private
Class properties and methods, that are set to be private, can only be accessed within a class, in other words only in which it is defined.
- Protected
Class properties and method, that are set to be protected, can only be accessed inside the class and by its subclasses, in other words its class and sub classes.
For a better understanding of Access Control modifiers in PHP, I have created a table structure to show them.
means access allow.
means access Not allow.
| Modifier Name | Within Class | Out Side Class | After Inheritance |
| Public |
|
|
|
| Private |
|
|
|
| Protected |
|
|
|
Simple Example of access controls
<?php
class className
{
//delaere variables with access modifier
public $variableName;
private $variableName;
protected $variableName;
//public method
public MethodName()
{
//body
}
//private method
private MethodName()
{
//body
}
protected MethodName()
{
//body
}
}
?>
Now each and every one, one by one.
Public access modifier
It is quite clear, the "public" access modifier achieves the highest level of accessibility. If you define your class properties and methods as "public", then it can be used anywhere in your PHP script.
Example of Public access modifier
In the following example, the class property and method of Myclass is set to be "public", and outside the class, an instance is created of Myclass. Then the "title" property is accessed by $obj and is assigned a "title" "ABCXYZ". Then the value of the title property is "$obj".
An instance is accessed again to display it, and finally the class method disptitle() is called by $obj, that will also display the value of the "title" property of the instance of the class. Since this method has an access to the title property, this is happening because of the class property and the method is public.
<?php
class Myclass
{
public $title;




Join the conversation! Your thoughts help the community grow.