Signup/Sign In

PHP Access Modifiers

To set the access rights for class methods and variables we use access modifiers which are nothing but PHP keywords. We can even assign some of these access modifiers to the class itself to make the class behave in a special way.

Following are the PHP keywords which are used as access modifiers along with their meaning:

  1. public: When we define class members as public, then they are accessible from anywhere, even from outside of the class scope.
  2. private: When we define class members as private, they can only be accessed from within the class itself.
  3. protected: This is same as private, with one exception, the class members defined as protected can still be accessed from its subclass(We will learn about subclasses when we will learn about Inheritance).
  4. abstract: This keyword is only used for PHP classes and its member functions.
  5. final: The class methods defined as final, can not be changed or overriden by any subclass.

When to use Which Access Modifier

We cannot use all the available access modifers with class, its varibales and methods. In the table below, we have specified which access specifier is applied to what:

Access Modiferclassesfunctionsvariables
publicNot ApplicableApplicableApplicable
privateNot ApplicableApplicableApplicable
protectedNot ApplicableApplicableApplicable
abstractApplicableApplicableNot Applicable
finalApplicableApplicableNot Applicable

Now that we know which access modifier is used where, lets learn about the access modifiers in details along with examples.


public Access Modifier

If we do not specify any access modifiers, all classes and its members are treated as public by default.

As mentioned in the table above, public, private or protected access modifiers cannot be used with class. Let's see what happens if we do,

<?php
    public class Studytonight {
        ...
    }
?>

Parse error: syntax error, unexpected 'public' (T_PUBLIC) in ...

We will get the above error.

But for class methods and variables we should specify the access specifiers although by default they are treated as public.

This is a simple example of a PHP class:

<?php
    class Studytonight {
        // to store name of person
        var $url = "studytonight.com";
        
        // simple class method
        function desc() {
            echo "Studytonight helps you learn Coding.";
        }
    }
?>

In the code above, we have used the keyword var before the class variable. If we do not use var, we will get a parse error.

But instead of using var we can also use access modifier keywords before the class variable decalaration, for example:

<?php
    class Studytonight {
        // to store name of person
        public $url = "studytonight.com";
        
        // simple class method
        function desc() {
            echo "Studytonight helps you learn Coding.";
        }
    }
?>

This is how we should create a PHP class, it is good programming practice to specify the access modifiers along with class varibles and methods.


private Access Modifier

We can use the private access modifier for class variables and methods but not for PHP class. When a class member - a variable or a function, is declared as private then it cannot be accessed directly using the object of the class. For example:

<?php
    class Person {
        // first name of person
        private $fname;
        // last name of person
        private $lname;
        
        // public function to set value for fname
        public function setFName($fname) {
            $this->fname = $fname;
        }
        
        // public function to set value for lname
        public function setLName($lname) {
            $this->lname = $lname;
        }
        
        // public function to 
        public function showName() {
            echo "My name is: " . $this->fname . " " . $this->lname;
        }
    }
    
    // creating class object
    $john = new Person();
    
    // trying to access private class variables
    $john->fname = "John";  // invalid
    $john->lname = "Wick";  // invalid
    
    // calling the public function to set fname and lname
    $john->setFName("John");
    $john->setLName("Wick");

?>

In the above code, $fname and $lname are private class variables, hence we cannot directly access them using the class object.

So, when we try to execute the following line of code:

<?php
    $john->setFName("John");
?>

We will get a fatal PHP error:

Fatal error: Cannot access private property Person::$fname in ...

But we can easily access the private variables of a class by defining public functions in the class. We can create separate functions to set value to private variables and to get their values too. These functions are called Getters and Setters.

<?php
    class Person {
        // first name of person
        private $name;
        
        // public function to set value for name (setter method)
        public function setName($name) {
            $this->name = $name;
        }
        
        // public function to get value of name (getter method)
        public function getName() {
            return $this->name;
        }
    }
    
    // creating class object
    $john = new Person();
    
    // calling the public function to set fname
    $john->setName("John Wick");
    
    // getting the value of the name variable
    echo "My name is " . $john->getName();

?>

My name is John Wick

We should have getter and setter methods for all the private variables in the class.


protected Access Modifier

Just like the private access modifier, protected access modifer also restricts the access of class variables and methods outside the class. But the protected class variables and functions can be accessed inside the class and inside the subclass(a class that inherits the class).

We will learn how to create a subclass and about the concept on Inheritance in the upcoming tutorials.

Let's take a quick and simple example:

<?php
    class Human {
        // protected variable
        protected $genders = array("Male", "Female", "Other");
        
        // protected function for humans features
        protected function getFeatures($gender) {
            if($gender == "Male") {
                echo "Men will be Men";
            }
            else if($gender == "Female") {
                echo "Women's mind is a maze.";
            }
            else if($gender == "Other") {
                echo "All are born equal.";
            }
        }
        
    }
    
    // subclass of the above class
    class Male extends Human {
        protected $gender = "Male";
        
        // public function to print Male features
        public function getMaleFeatures() {
            // calling the protected getFeatures() method of class Human
            $this->getFeatures($this->gender);
        }
    }
    
    // object of Human class
    $human = new Human();
    // object of Male class
    $male = new Male();
    
    /*  
        accessing protected variables and methods
    */
    echo $human->genders;   // INVALID
    $human->getFeatures("Male");    // INVALID
    echo $male->gender;     // INVALID
    
    /*
        but we can call getMaleFeatures method,
        in which we are calling a protected method 
        of Human class
    */
    $male->getMaleFeatures();

?>

In the program above, we have defined two classes, Human and Male. The class Male is a subclass of the Human class.

In the Human class all the class variables and methods are protected, hence they cannot be accessed from outside the class, but they can be accessed inside the subclass of the class Human.

Don't worry if this looks confusing due to the concept of Inheritance, we will again re-visit this, when we will learn about Inheritance.


abstract Access Modifier

The abstract access modifier is used with PHP class and its functions. It cannot be used for class variables.

If a class has even a single abstract method. then the class must also be defined as abstract.

Also, PHP doesn't allow instantiating the abstract class i.e. you cannot create object of an abstract class, although these classes can be inherited.

We will learn about this access modifier in detail when we will cover Abstract class and Interfaces.


final Access Modifier

When we declare a class as final, using this access modifier, then that class cannot be inherited.

Similarly, when we define a class function as final, PHP restricts the subclasses of that class from overriding that function which is declared as final.

Again, we will explain this with help of examples when we will learn about Inheritance.