In this blog page, you will learn about PHP access modifiers and understand the differences between them.
Public
, Private
, and Protected
.
Public – By Using this access modifier, class members will be publicly accessible from anywhere, even from outside the scope of the class. by default the classes are Public
Private – BY using this keyword, class members will be accessed within the class itself. It protects members from outside class access with the reference of the class instance.
Protected – This is the same as private modifier, with one exception, the class members defined as protected can still be accessed from its subclass or child class.
PHP – Access Modifiers in Oops With Example
Public & private Access Modifier:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <?php class Person { // name of person private $name; // Age private $age; // public function to set value for name public function setName($name) { $this->name = $name; } // public function to set value for age public function setAge($age) { $this->age= $age; } // public function to public function showPersonDetails() { echo "My name is: " . $this->name. ", Age: " . $this->age; } } // creating class object $john = new Person(); // trying to access private class variables $john->name= "Jateen"; // invalid $john->age= "34"; // invalid // calling the public function to set name and age $john->setName("Jateen"); // it will work $john->setAge("34"); // it will work ?> |
Protected Access modifier
Protected members can only be accessible inside the derived class or child class. See the below example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <?php // Parent class class OnlineTest { protected $x=500; protected $y=100; function add() { echo $sum=$this->x + $this->y; } } // Child Class class Child extends OnlineTest { function sub() { echo $sub=$this->x - $this->y; } } $objchild= new Child; $objpar = new OnlineTest $objchild->add(); // valid $objchild->sub(); // valid $objpar->x; // invalid ?> |
The above example $objpar is the object of the parent class and $x is the protected
member variable, So it can not be accessed directly outside of the class but it can access inside the child class.
Questions asked in Interview on Oops Access Modifiers:
- What is an Access modifier in PHP?
- What Is a Protected Access modifier?
- Can we use Public, Private, and protected as before Class?