PHP Access Modifiers

by Vincy. Last modified on July 9th, 2022.

PHP access modifiers are used to set access rights with PHP classes and their members which are the functions and variables defined within the class scope.

In PHP, there are some keywords representing these access modifiers. These keywords will be added with PHP classes and their members.

PHP keywords as Access Control Modifiers

Now, let us have a look at the following list to know about the possible PHP keywords used as access modifiers.

  1. public – class or its members defined with this access modifier will be publicly accessible from anywhere, even from outside the scope of the class.
  2. private – class members with this keyword will be accessed within the class itself. It protects members from outside class access with the reference of the class instance.
  3. protected – same as private, except by allowing subclasses to access protected superclass members.
  4. abstract – This keyword can be used only for PHP classes and their functions. For containing abstract functions, a PHP class should be an abstract class.
  5. final – It prevents subclasses to override superclass members defined with the final keyword.

Access modifiers Usage with PHP Classes, Class Members

Based on the possibility of applying the above list of PHP access modifiers, we can classify them. The following tabular column specifies which keyword could be applied wherein classes, functions or methods.

access modifier classes functions variable
public Not Applicable Applicable Applicable
private Not Applicable Applicable Applicable
protected Not Applicable Applicable Applicable
abstract Applicable Applicable Not Applicable
final Applicable Applicable Not Applicable

public Access Modifier

Before introducing access modifiers in PHP, all classes and their members are treated as public by default. Still, for PHP classes without specifying any access modifiers, then it will be treated as public.

If we specify public, private, or protected for a PHP class, then it will cause the parse error. For example, if we define a class as,

<?php
public class  {
}
?>

Then, the following parse error will be displayed to the browser.

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

Similarly, class functions without any access modifiers will be treated as public functions. But, it is good programming practice to specify those functions as public for better understanding.

Unlike PHP classes and functions, we need to specify access modifiers for PHP class variables explicitly. For example, the following code is invalid, which will cause PHP parse error.

<?php
class Toys {
    $categories = array(
    "puzzles",
    "pull back",
    "remote",
    "soft"
);
}
?>

And, the valid code for defining classes with public variables follows.

<?php

class Toys
{

    public $categories = array(
        "puzzles",
        "pull back",
        "remote",
        "soft"
    );
}
?>

private Access Modifier

We can state this keyword only for class variables and functions, but not for the class itself, like as a public modifier. PHP class members defined as private cannot be accessed directly by using its instance. For example,

<?php

class Toys
{

    private $categories = array(
        "puzzles",
        "pull back",
        "remote",
        "soft"
    );

    public function getToysCategories()
    {
        return $this->categories;
    }
}
$objToys = new Toys();
print "<pre>";
print_r($objToys->categories); // invalid
print_r($objToys->getToysCategories());
print "</pre>";
?>

In the above program, the Toys class contains a private variable and a public function. Accessing this private variable by using the Toys class instance with the line,

<?php
print_r($objToys->categories); // invalid
?>

will cause PHP fatal error as,

Fatal error:  Cannot access private property Toys::$categories in ...

But we can access class private variables via any public function of that class. In the above program, we are getting the elements of $categories array variables via getToysCategories() function defined as public.

Note that, all members of a class can be accessed within the class scope by using $this variable.

protected Access Modifier

This keyword is used in a PHP program that is using PHP inheritance. And, it is used to prevent access to PHP classes and their members from anywhere, except from inside the class itself or from inside its subclasses.

With this keyword, PHP classes and their member functions cannot be accessed directly from outside the classes and their subclasses, with the references to their instance.

Consider the following PHP program.

<?php

class Toys
{

    protected $categories = array(
        "puzzles",
        "pull back",
        "remote",
        "soft"
    );

    protected $toys = array(
        array(
            "name" => "Mechanical Cars",
            "category" => "pull back"
        ),
        array(
            "name" => "Jigsaw",
            "category" => "puzzles"
        ),
        array(
            "name" => "HiTech Cars",
            "category" => "remote"
        ),
        array(
            "name" => "Teddy Bears",
            "category" => "soft"
        ),
        array(
            "name" => "Baby pillow",
            "category" => "soft"
        ),
        array(
            "name" => "Chinese Checker",
            "category" => "puzzles"
        ),
        array(
            "name" => "Electronic Toys",
            "category" => "remote"
        )
    );

    protected function getToys()
    {
        for ($i = 0; $i < count($this->toys); $i ++) {
            $toys_list[] = $this->toys[$i]["name"];
        }
        return $toys_list;
    }

    protected function getToysByCategory($category)
    {
        for ($i = 0; $i < count($this->toys); $i ++) {
            if ($this->toys[$i]["category"] == $category)
                $toys_list[] = $this->toys[$i]["name"];
        }
        return $toys_list;
    }
}

class SoftToys extends Toys
{

    protected $category = "soft";

    function getToys()
    {
        return $this->getToysByCategory($this->category);
    }
}

$objToys = new Toys();
$objSoftToys = new SoftToys();
print "<pre>";
/**
 * Invalid
 * print_r($objToys->categories);
 * print_r($objSoftToys->categories);
 * print_r($objToys->getToys());
 */
print_r($objSoftToys->getToys());
print "</pre>";
?>

In this program, we can see some of the statements are commented on. These are invalid attempts to access protected members from outside Toys class.

We can access these members, as we have done with private member access by using the public function of a class.

abstract Access Modifier

We can define a PHP class or its function as abstract, but, abstractly is not applicable for class variables. For having at least one abstract function in a PHP class, then that class should be an abstract class.

We cannot access PHP abstract class members with its instance. Because PHP restricts instantiating the abstract class and causes the following error message while creating such an instance.

Fatal error: Cannot instantiate abstract class ...

But we can inherit an abstract class. Simply say, PHP abstract classes are behaving like PHP interfaces. For an abstract class, we cannot contain any abstract function definition. Rather, we should just declare a function. For defining it, we should inherit this abstract class for a non-abstract subclass to have a function definition.

The following code is an example of a PHP abstract modifier.

<?php

abstract class Toys
{

    public $categories = array(
        "puzzles",
        "pull back",
        "remote",
        "soft"
    );

    public $toys = array(
        array(
            "name" => "Mechanical Cars",
            "category" => "pull back"
        ),
        array(
            "name" => "Jigsaw",
            "category" => "puzzles"
        ),
        array(
            "name" => "HiTech Cars",
            "category" => "remote"
        ),
        array(
            "name" => "Teddy Bears",
            "category" => "soft"
        ),
        array(
            "name" => "Baby pillow",
            "category" => "soft"
        ),
        array(
            "name" => "Chinese Checker",
            "category" => "puzzles"
        ),
        array(
            "name" => "Electronic Toys",
            "category" => "remote"
        )
    );

    abstract function getToys();

    function getToysByCategory($category)
    {
        for ($i = 0; $i < count($this->toys); $i ++) {
            if ($this->toys[$i]["category"] == $category)
                $toys_list[] = $this->toys[$i]["name"];
        }
        return $toys_list;
    }
}

class SoftToys extends Toys
{

    protected $category = "soft";

    function getToys()
    {
        return $this->getToysByCategory($this->category);
    }
}

$objSoftToys = new SoftToys();
print "<pre>";
print_r($objSoftToys->getToys());
print "</pre>";
?>

final Access Modifier

With PHP final access modifier classes are prevented from inheriting them. If we attempt to derive subclasses from PHP final classes, then the following fatal error will occur to stop program execution.

Fatal error: Class SoftToys may not inherit from final class ...

PHP’s final keyword should be used for PHP classes and functions, but not for class properties or variables. PHP functions with the final keyword will not be overridden.

Download PHP Access Modifiers Source Code

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “PHP Access Modifiers”

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page