Access Specifiers in PHP

There are 3 types of Access Specifiers available in PHP, Public, Private and Protected.

Public – class members with this access modifier will be publicly accessible from anywhere, even from outside the scope of the class.

Private – class members with this keyword will be accessed within the class itself. It protects members from outside class access with the reference of the class instance.

Protected – same as private, except by allowing subclasses to access protected superclass members.

EXAMPLE 1: Public

<?php  
class demo  
{  
public $name="php";  
functiondisp()  
{  
echo $this->name."<br/>";  
}  
}  
class child extends demo  
{  
function show()  
{  
echo $this->name;  
}  
}     
$obj= new child;  
echo $obj->name."<br/>";     
$obj->disp();  
$obj->show();  
?>  

Output:

php

php

php

EXAMPLE 2: Private

<?php  
classJavatpoint  
{  
private $name="Sonoo";  
private function show()  
{  
echo "This is private method of parent class";  
}  
}     
class child extends Javatpoint  
{  
function show1()  
{  
echo $this->name;  
}  
}     
$obj= new child;  
$obj->show();  
$obj->show1();  
?>  

Output:

Access Specifiers in PHP

EXAMPLE 3: Protected

  

<?php  
classJavatpoint  
{  
protected $x=500;  
protected $y=100;  
    function add()  
{  
echo $sum=$this->x+$this->y."<br/>";  
}  
    }     
class child extends Javatpoint  
{  
function sub()  
{  
echo $sub=$this->x-$this->y."<br/>";  
}  
  
}     
$obj= new child;  
$obj->add();  
$obj->sub();  
  
?>

Output:

600

400

EXAMPLE 4: Public,Private and Protected

<?php  
classJavatpoint  
{    
public $name="Ajeet";  
protected $profile="HR";   
private $salary=5000000;  
public function show()  
{  
echo "Welcome : ".$this->name."<br/>";  
echo "Profile : ".$this->profile."<br/>";  
echo "Salary : ".$this->salary."<br/>";  
}  
}     
classchilds extends Javatpoint  
{  
public function show1()  
{  
echo "Welcome : ".$this->name."<br/>";  
echo "Profile : ".$this->profile."<br/>";  
echo "Salary : ".$this->salary."<br/>";  
}  
}     
$obj= new childs;     
$obj->show1();  
?>  

Output:

Access Specifiers in PHP