PHP MySQL tutorial

Access Modifiers in PHP

In the articles related to object oriented programming, we studied how we can define a class which contains member variables and functions. This article focuses on defining scope of those member variables and functions. By Scope we mean visibility of a member variable or a function within the class, outside the class and the child classes. The visibility of these class members is defined by access modifiers. There are three types of access modifiers in PHP.


By default all the class members are public. Public members of the class are accessible by other members in the same class, by the members outside the class and the members in the child class. In short, public members of a class are accessible everywhere.


Private members of a class are only accessible within the class and are nor accessible by the other classes neither by the child classes.


Protected members of a class are accessible only within the class itself and the child classes.

Let’s have a look at the following example to see how access modifiers actually work in PHP.

       //Private function accessible only in this class
      private function PrivFunc(){
         echo "I am a private function";
      // I am protected function accessible in child only
      protected function ProtFunc(){
         echo "I am a protected function.
"; } } // Child class extending Base class Derived extends Base { // Accessing Private Base class function function CallToProtected() { parent:: ProtFunc(); } // Accessing Public function of base class function CallToPublic() { parent:: PubFunc(); } } class Random { // Accessing public funcion of base class function CallToPublic() { $baseclass = new Base(); $baseclass -> PubFunc(); } } // Creating objects of Item class. $derived = new Derived(); $derived -> CallToProtected(); $derived -> CallToPublic(); $random = new Random(); $random -> CallToPublic(); ?>

Download the code
Run the code

In the above code, a base class has been defined which contains one Public, Private and Protected function. Next a child class has been defined which contains functions which in turn call to public and protected functions of the base class. Finally some random class has been defined which contains function where object of Base class is being created and private function is being called through it.

<<< Commonly Used String Functions in PHPVariable Examination Functions in PHP >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .