Spread the love

In object oriented programming(oops) to set the visibility of classes, variables and methods we are using access modifiers.

So Access modifiers are used the encapsulation of class properties.

There are three types of access modifiers in any language (Php, java or c etc. )

  1. Private
  2. Protected
  3. Public

1. Private Access modifiers
Private access modifiers can only be used in to encapsulate the property of class. we cannot access private property outside the class or in child class as well


Class MyClass{
    private $tax=10; //private property
    public function calculatePrice($amount){
        return  $this->tax+$amount;                 // we can only use private property within class
    public function getTaxValue(){
        return  $this->tax;                 // private property within class

$MyClass    =   new MyClass();
$MyClass->tax;              //will generate error
echo $MyClass->getTaxValue();    //  will show the value of $tax
                                 // because we are using public function
                                 // to get the private value of  $tax  

2. Protected access Modifiers

This type of modifiers can be used in within class or child class, So it means protected properties are used in inheritance.


Class MyClass{
    private $tax=10; //private property
    protected $parent="test" //protected property

    private function calculatePrice($amount){
        return  $this->tax+$amount;                 // we can only use private property within class
    public function getTaxValue(){
        return  $this->tax;                 // private property within class
    protected function check(){
           $this->tax;                 // private property within class
           $this->parent;                 // protected accessible within class

class MyclassChild extends MyClass{
    public function callParent(){

        $this->check();         //  // protected accessible in child class
        $this->calculatePrice(); // will generate errror 



$MyclassChild    =   new MyclassChild();
$MyclassChild->callParent();   // public method      

3. Public Access Modifiers

This type of modifiers can be used anywhere. They are not bounded to any class, child class or outside the class. So as you see in above example public methods and properties are accessible in class or outside the class as well.

Leave a Reply