PHP OOP – Access Modifiers

Welcome to The Coding College! In this tutorial, we will dive into access modifiers in PHP Object-Oriented Programming (OOP). Access modifiers define the visibility and accessibility of properties and methods in a class, ensuring better control, security, and encapsulation of your code.

What Are Access Modifiers?

Access modifiers are keywords used in PHP to control the visibility of class properties and methods. They determine who can access or modify class members (properties and methods). PHP provides three types of access modifiers:

  1. Public
  2. Protected
  3. Private

Types of Access Modifiers

1. Public

The public access modifier allows the property or method to be accessed from anywhere in your code:

  • Inside the class.
  • Outside the class.
  • By inherited (child) classes.

Example: Public Modifier

  • Here, the $brand property and setBrand() method are public, so they can be accessed directly outside the class.

2. Protected

The protected access modifier allows the property or method to be accessed:

  • Inside the class where it is declared.
  • Inside child classes that inherit from the parent class.
  • Cannot be accessed from outside the class or by an object of the class.

Example: Protected Modifier

<?php
class Vehicle {
    protected $type; // Protected property

    protected function setType($type) {
        $this->type = $type; // Protected method
    }
}

class Bike extends Vehicle {
    public function setBikeType($type) {
        $this->setType($type); // Accessing protected method from parent class
        return "Bike type is $this->type.";
    }
}

$bike = new Bike();
echo $bike->setBikeType("Mountain Bike"); // Output: Bike type is Mountain Bike
?>
  • The setType() method and $type property are protected, so they cannot be accessed directly by the object but are available to child classes.

3. Private

The private access modifier allows the property or method to be accessed:

  • Only within the class where it is declared.
  • Cannot be accessed by child classes or from outside the class.

Example: Private Modifier

<?php
class Person {
    private $name; // Private property

    private function setName($name) {
        $this->name = $name; // Private method
    }

    public function setAndGetName($name) {
        $this->setName($name); // Access private method within the class
        return $this->name;
    }
}

$person = new Person();
echo $person->setAndGetName("John"); // Output: John

// Trying to access private members will cause an error:
// $person->setName("John"); // Fatal Error
// echo $person->name; // Fatal Error
?>
  • The $name property and setName() method are private, so they can only be accessed inside the Person class.

Comparison Table of Access Modifiers

ModifierInside ClassChild ClassesOutside Class
Public
Protected
Private

Why Use Access Modifiers?

  1. Encapsulation: Keeps sensitive data hidden from external code.
  2. Control: Allows fine-tuned control over how properties and methods are accessed or modified.
  3. Security: Prevents unintended access or modification of properties and methods.

Real-World Example: Access Modifiers in Action

Let’s demonstrate a scenario where we use public, protected, and private access modifiers in an e-commerce application.

<?php
class Product {
    private $price;          // Can only be accessed within the Product class
    protected $discount;     // Can be accessed by child classes
    public $name;            // Can be accessed by anyone

    public function __construct($name, $price) {
        $this->name = $name;
        $this->price = $price;
    }

    private function calculateFinalPrice() {
        return $this->price - ($this->price * $this->discount / 100);
    }

    public function setDiscount($discount) {
        $this->discount = $discount;
    }

    public function getFinalPrice() {
        return $this->calculateFinalPrice();
    }
}

class Electronics extends Product {
    public function applyElectronicsDiscount() {
        $this->discount = 10; // Access protected property
    }
}

// Create a product object
$tv = new Electronics("Smart TV", 1000);
$tv->applyElectronicsDiscount(); // Set a discount for electronics
echo $tv->getFinalPrice(); // Output: 900

// Direct access to private property will cause an error:
// echo $tv->price; // Fatal Error
?>

Key Points About Access Modifiers

  1. Public: Open access to everyone (ideal for properties and methods meant for general use).
  2. Protected: Limits access to the class and its child classes (ideal for properties shared between parent and child).
  3. Private: Restricts access to the class itself (ideal for sensitive data).

Best Practices for Using Access Modifiers

  1. Keep properties private: Direct access to properties breaks encapsulation. Use getter and setter methods for controlled access.
  2. Use protected for inheritance: Share common logic between parent and child classes.
  3. Expose public methods cautiously: Only expose methods that are meant for general use.

Conclusion

Access modifiers are a powerful feature in PHP OOP that help you control how properties and methods are accessed and used. By using public, protected, and private effectively, you can build more secure, flexible, and maintainable applications.

To explore more PHP OOP concepts and practical examples, visit The Coding College.

Leave a Comment