Access Modifiers

Last updated on

PHP access modifiers (public, protected, and private) are boundaries. Each one lets you control how different parts of your code interact with each other, which makes your project cleaner, more secure, and easier to manage.

In the following sections, you will understand what each of these access modifiers does and why it matters.

What Are Access Modifiers?

Access modifiers help you to define the visibility of properties and methods. You use them to specify who gets to access different parts of your classes.

In the following list, you will see the three types of access modifiers:

  • Public: Everyone can access it, whether they are in the same class, a subclass, or even completely outside of your code structure.
  • Protected: Only your class and its child classes can access it.
  • Private: Strictly limited to the class itself.

These keywords set direct tasks that keep your code from becoming chaotic and help you avoid unexpected bugs.

Let’s get started with each one and look at examples to see how they can work in PHP.

Role of "Public" in PHP Access Modifiers

When you label something as public, you are allowed full access to it from anywhere. Public properties and methods can be called or modified from inside or outside of the class, giving you the ability to make certain parts of your class accessible throughout your entire application.

class Car {
    public $color;

    public function setColor($color) {
        $this->color = $color;
    }
}

$myCar = new Car();
$myCar->setColor('red');
echo $myCar->color; // Output: red

So, both $color and setColor() are public. This openness is helpful for things like settings or data that need to be widely accessible.

Anyway, let's see another label in access modifiers "protected".

Protected: Limited Accessibility in Access Modifiers

If you need more control, you can use "protected" keyword beside the main syntax of class. This modifier restricts access to the class itself and any classes that extend it. So, while you can access it from within the class hierarchy, it stays off-limits to anything outside.

This makes protected a good choice for properties or methods that should only be accessed within the class structure but shouldn’t be exposed elsewhere.

Here is an example to show how protected works: 

class Car {
    protected $fuelLevel;

    protected function setFuelLevel($level) {
        $this->fuelLevel = $level;
    }
}

class ElectricCar extends Car {
    public function chargeBattery() {
        $this->setFuelLevel(100);
    }
}

$tesla = new ElectricCar();
$tesla->chargeBattery();
// Attempting to access setFuelLevel() or $fuelLevel from outside would cause an error

If you see $fuelLevel and setFuelLevel(), you will find they are labeled as protected, so only Car and its child classes like ElectricCar can access them. If you try to use them directly from outside the class, PHP will throw an error.

Anyway, in the following section, you will learn how to use "private" in access modifiers.

Using "Private" in Access Modifiers

When you need to keep certain data or functionality strictly within the class, private can do this task. Private properties and methods are fully encapsulated in the class, so no one outside the class can access or change them—not even subclasses.

This is ideal for sensitive data or internal logic that you want to protect from any accidental changes outside the class.

Here is an example:

class BankAccount {
    private $balance;

    public function __construct($amount) {
        $this->balance = $amount;
    }

    private function updateBalance($amount) {
        $this->balance += $amount;
    }

    public function deposit($amount) {
        $this->updateBalance($amount);
    }
}

$account = new BankAccount(100);
$account->deposit(50);
// Direct access to $balance or updateBalance() from outside will result in an error

Here, $balance and updateBalance() are marked as private, so only the BankAccount class can access them. The only way to adjust the balance is by calling deposit(). This keeps the class safe from any external meddling, preserving its integrity.

Wrapping Up

Access modifiers are small keywords that make a big impact, allowing you to protect sensitive data, avoid accidental changes, and define clear roles within your code.

So, when you write a class, consider which methods and properties should be public, protected, or private.

That's all, if you need more tutorials in PHP, click here. Thank you for reading.  

Frequently Asked Questions (FAQs)

  • What are access modifiers in PHP?

    Access modifiers in PHP (public, protected, and private) define the visibility and accessibility of properties and methods in a class. They help you control which parts of your code can access certain data, making your code more secure and organized.
  • What does 'public' mean in PHP?

    In PHP, public means that a property or method can be accessed from anywhere: within the class, in any subclass, and even outside of the class structure. For example:
    class Car {
        public $color;
    
        public function setColor($color) {
            $this->color = $color;
        }
    }
    
    $myCar = new Car();
    $myCar->setColor('red');
    echo $myCar->color; // Output: red
    
  • What does 'protected' mean in PHP?

    protected properties or methods are accessible only within the class they’re declared in and any subclasses that extend this class. However, they cannot be accessed from outside. Here’s an example:
    class Car {
        protected $fuelLevel;
    
        protected function setFuelLevel($level) {
            $this->fuelLevel = $level;
        }
    }
    
    class ElectricCar extends Car {
        public function chargeBattery() {
            $this->setFuelLevel(100);
        }
    }
    
    $tesla = new ElectricCar();
    $tesla->chargeBattery();
    // Accessing setFuelLevel() or $fuelLevel outside will cause an error
    
  • What does 'private' mean in PHP?

    private restricts the property or method to the class in which it is declared. This means neither subclasses nor external code can access private properties or methods. Here’s how private works:
    class BankAccount {
        private $balance;
    
        public function __construct($amount) {
            $this->balance = $amount;
        }
    
        private function updateBalance($amount) {
            $this->balance += $amount;
        }
    
        public function deposit($amount) {
            $this->updateBalance($amount);
        }
    }
    
    $account = new BankAccount(100);
    $account->deposit(50);
    // Direct access to $balance or updateBalance() outside will result in an error
    
  • Can I access a 'protected' property outside of the class?

    No, you cannot directly access a protected property from outside the class it is declared in or from any subclasses. Trying to do so will lead to an error. protected is meant to allow access within the class and any subclasses only.
  • When should I use 'private' instead of 'protected'?

    Use private when you want a property or method to be completely encapsulated within the class, hidden from any outside access, including subclasses. This is useful for sensitive data or methods that shouldn’t be modified outside the class itself.
  • What is the difference between 'protected' and 'private'?

    The difference is in accessibility. protected allows access within the class and its subclasses, while private restricts access strictly to the class where it is defined.
  • Can subclasses inherit 'private' properties?

    No, private properties and methods are not accessible in subclasses. They are exclusive to the class where they are defined. If a subclass needs access, consider using protected instead.
Share on: