Home >>PHP Object Oriented >PHP Access Modifier

PHP Access Modifier

Public Private Protected in PHP

Access Modifier allows you to alter the visibility of any class member(properties and method). In php 5 there are three scopes for class members.
  • Public
  • Protected and
  • Private

Public Access modifier

Public access modifier is open to use and access inside the class definition as well as outside the class definition.
<?php

class demo

{

public $name="ravish";

function disp()

{

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 ravish ravish ravish
In the above example Create a demo class with a public property $name and method disp( ). create a child class of demo class(using inheritance) with a method show( ). inside show( ) method of child class call the global property of parent class(demo). Now create the object of child class, call its own method show(), its parent class method disp( ) and parent class property $name.

Protected access modifier

Protected is only accessible within the class in which it is defined and its parent or inherited classes.
<?php

class demo

{

protected $x=500;

protected $y=500;
		
function add()
{

echo $sum=$this->x+$this->y."<br/>";

}
		
}	


class child extends demo

{

function sub()

{

echo $sub=$this->x-$this->y."<br/>";

}

}	

$obj= new child;

$obj->add();

$obj->sub();

?>
Output 1000 0

Private access modifier

Private is only accessible within the class that defines it.( it can't be access outside the class means in inherited class).
<?php

class demo

{

private $name="shashi";

private function show()

{

echo "This is private method of parent class";

}

}	


class child extends demo

{

function show1()

{

echo $this->name;

}

}	

$obj= new child;

$obj->show();

$obj->show1();

?>
Output Fatal error: Call to private method demo::show()

use of all access modifier in a single example

Create a parent class with public, private and protected properties and try to access these properties with their child class. Eg(summary)
<?php

class parents

{  

public $name="shashi";

protected $profile="developer"; 

private $salary=50000;

public function show()

{

echo "Welcome : ".$this->name."<br/>";

echo "Profile : ".$this->profile."<br/>";

echo "Salary : ".$this->salary."<br/>";

}

}	

class childs extends parents

{

public function show1()

{

echo "Welcome : ".$this->name."<br/>";

echo "Profile : ".$this->profile."<br/>";

echo "Salary : ".$this->salary."<br/>";

}

}	

$obj= new childs;	

$obj->show1();

?>
Output Welcome : shashi Profile : developer Salary :

No Sidebar ads