Tutorial on PHP Access Modifiers

Access modifiers in PHP control the visibility of properties and methods in a class. They determine where and how class members (properties and methods) can be accessed. PHP supports three main access modifiers:

  1. public: Accessible from anywhere.
  2. protected: Accessible only within the class itself and by inheriting classes.
  3. private: Accessible only within the class where they are declared.

This tutorial covers:

1. Basics of Access Modifiers

Access modifiers are declared before the property or method in a class.

Example: Using Access Modifiers

<?php
class Example {
    public $publicProperty = "I am public";
    protected $protectedProperty = "I am protected";
    private $privateProperty = "I am private";

    public function showProperties() {
        echo $this->publicProperty . "\n";
        echo $this->protectedProperty . "\n";
        echo $this->privateProperty . "\n";
    }
}

$example = new Example();
$example->showProperties(); // Accessing within the class

// Accessing properties from outside the class
echo $example->publicProperty . "\n";  // Accessible
// echo $example->protectedProperty;  // Error
// echo $example->privateProperty;    // Error
?>

Output:

I am public
I am protected
I am private
I am public

2. public Modifier

  • Members declared as public are accessible everywhere: inside the class, outside the class, and in derived classes.

Example: Public Members

<?php
class Car {
    public $brand;

    public function setBrand($brand) {
        $this->brand = $brand;
    }

    public function getBrand() {
        return $this->brand;
    }
}

$car = new Car();
$car->setBrand("Toyota");
echo $car->getBrand(); // Accessible from outside
?>

Output:

Toyota

3. protected Modifier

  • Members declared as protected are accessible within the class and in derived classes but not from outside the class.

Example: Protected Members

<?php
class Animal {
    protected $type;

    public function setType($type) {
        $this->type = $type;
    }

    protected function getType() {
        return $this->type;
    }
}

class Dog extends Animal {
    public function showType() {
        return "This is a " . $this->getType();
    }
}

$dog = new Dog();
$dog->setType("Mammal");
echo $dog->showType(); // Accessible through a public method in the derived class
// echo $dog->type;     // Error
?>

Output:

This is a Mammal

4. private Modifier

  • Members declared as private are accessible only within the class where they are declared, not in derived classes or outside the class.

Example: Private Members

<?php
class BankAccount {
    private $balance;

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

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

    public function getBalance() {
        return $this->balance;
    }
}

$account = new BankAccount(1000);
$account->deposit(500);
echo $account->getBalance(); // Accessible through a public method
// echo $account->balance;    // Error
?>

Output:

1500

5. Practical Examples

Example 1: Role-Based Access

<?php
class User {
    public $username;
    protected $role;

    public function __construct($username, $role) {
        $this->username = $username;
        $this->role = $role;
    }

    protected function getRole() {
        return $this->role;
    }

    public function displayRole() {
        return "{$this->username} is a {$this->getRole()}";
    }
}

class Admin extends User {
    public function hasAdminAccess() {
        return $this->getRole() === "Admin";
    }
}

$admin = new Admin("John", "Admin");
echo $admin->displayRole();  // Access through public method
// echo $admin->getRole();   // Error
?>

Output:

John is a Admin

Example 2: Securing Sensitive Data

<?php
class SecureData {
    private $pinCode;

    public function setPin($pin) {
        if (is_numeric($pin) && strlen($pin) === 4) {
            $this->pinCode = $pin;
            return "PIN set successfully.";
        }
        return "Invalid PIN.";
    }

    public function verifyPin($pin) {
        return $this->pinCode === $pin ? "Access Granted" : "Access Denied";
    }
}

$data = new SecureData();
echo $data->setPin(1234) . "\n";
// echo $data->pinCode;     // Error
echo $data->verifyPin(1234) . "\n";
echo $data->verifyPin(5678) . "\n";
?>

Output:

PIN set successfully.
Access Granted
Access Denied

6. Encapsulation with Getter and Setter Methods

Encapsulation is the principle of restricting direct access to class members and providing controlled access through methods.

Example: Encapsulation

<?php
class Product {
    private $price;

    public function setPrice($price) {
        if ($price > 0) {
            $this->price = $price;
        } else {
            echo "Invalid price.\n";
        }
    }

    public function getPrice() {
        return $this->price;
    }
}

$product = new Product();
$product->setPrice(200);
echo "Price: " . $product->getPrice() . "\n";
$product->setPrice(-50); // Invalid
?>

Output:

Price: 200
Invalid price.

Summary of Access Modifiers

Modifier Access from Same Class Access from Derived Class Access from Outside
public Yes Yes Yes
protected Yes Yes No
private Yes No No

Key Takeaways

  1. Use public for members that need to be accessed everywhere.
  2. Use protected for members that should be shared with derived classes but hidden from outside.
  3. Use private to keep sensitive data and methods strictly within the class.
  4. Leverage encapsulation (getters and setters) for controlled access to private properties.

Access modifiers enhance data security and code maintainability, ensuring a clean and logical structure in your PHP projects.

Related posts

PHP Static Methods: A Tutorial with Examples

PHP Deleting Files: A Tutorial with Examples

PHP Copying Files: A Tutorial with Examples