PHP Access Modifier

PHP Access Modifier


Access modifiers are object-oriented programming that is used to set the accessibility of classes, constructors, methods, and other members of php.
Using the access modifiers we can set the scope or accessibility of these classes, methods, constructors, and other members. 

There are three types of access modifier in PHP :

Public – When you create a properties and functions  in the PHP class and do not specify the access modifier, it is set to public by default. In this mode, the properties and functions is accessible everywhere.

Private – When you create a properties and functions with a private access modifier, it is accessible only within the class in which it is created.

Protected – Protected properties and functions is accessible within the class in which it is created. Also, the classes derived from this class can its a protected properties and functions

Public : Public property and method can access anywhere.

Let's understand with given below example :

Output : My name :Alex and my age is : 30

Private:We can use the private access modifier for class variables and methods but not for PHP class. When a class member - a variable or a function, is declared as private then it cannot be accessed directly using the object of the class.

For example given below :

Output :

Protected : This keyword is used in a PHP program which is using PHP inheritance. And, it is used to prevent access to PHP classes and its members from anywhere, except from inside the class itself or from inside its subclasses.

With this keyword, PHP classes and its member’s functions cannot be access directly from outside the classes and their subclasses, with the references to their instance.

Example : 

Output : 600
               400