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

snippet
<?php
class demo
{
public $name="Ajeet";
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:

Access Specifiers in PHP

EXAMPLE 2: Private

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

Output:

Access Specifiers in PHP

EXAMPLE 3: Protected

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

}	
$obj= new child;
$obj->add();
$obj->sub();

?>

Output:

Access Specifiers in PHP

EXAMPLE 4: Public,Private and Protected

snippet
<?php
classrookienerd
{  
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 rookienerd
{
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
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +