PHP Access Specifiers

There are the three access specifiers in PHP: Public, Protected & Private.
These access specifiers can apply on both properties and methods. If no access specifiers is written then by default it is public.

Public Access Specifier

Public properties and methods are accessible inside and outside of the class.

Example

<?php
    class Corporate {
        public $country = 'India';
        public function welcome($empname) {
            $msg = 'Hello '.$empname.', welcome to '.$this->country;
            return $msg;
        }
    }
    $obj1 = new Corporate();
    echo $obj1->country;
    echo $obj1->welcome('john');
?>

In the above example, $obj1->country will display the defined country name as the variable $country has declared as public.





Protected Access Specifier

Protected access specifier is generally used with inheritance. The properties and methods declared as protected can be accessible within the class and the inheriting class or child class.

Example

<?php
    class Corporate {
        protected $country = 'India';
    }
    class Company extends Corporate {
        public function welcome(){
            $msg = 'Welcome to '.$this->country;
            return $msg;
        }
    }
    $obj1 = new Company();
    echo $obj1->country; // Fatal error: Cannot access protected property
    echo $obj1->welcome();
?>

In the above example, $obj1->country will display an error as country variable has declared as protected. This is accessible by its member function and the derived class only.


Private Access Specifier

Private access specifier is available within the class only. This is used to hide the properties and methods to the outside of the class. A child class does not know parents private properties and methods.

Example

<?php
    class Corporate {
        private $country = 'India';
        public function welcome($empname) {
            $msg = 'Hello '.$empname.', welcome to '.$this->country;
            return $msg;
        }
        
    }
    $obj1 = new Corporate();
    echo $obj1->country; //Fatal error: Cannot access private property
    echo $obj1->welcome('john');
?>

In the above example, $obj1->country will display fatal error, as $country variable has declared as private. This is accessible by its member function only.