Start Coding

Topics

PHP Access Modifiers

Access modifiers are keywords used in object-oriented PHP to control the visibility and accessibility of properties and methods within classes. They play a crucial role in encapsulation, one of the fundamental principles of OOP.

Types of Access Modifiers

PHP supports three main access modifiers:

  • public: Accessible from anywhere
  • private: Accessible only within the declaring class
  • protected: Accessible within the declaring class and its child classes

Public Access Modifier

Public properties and methods can be accessed from anywhere, both inside and outside the class.


class Car {
    public $color = "red";
    public function startEngine() {
        echo "Engine started!";
    }
}

$myCar = new Car();
echo $myCar->color; // Outputs: red
$myCar->startEngine(); // Outputs: Engine started!
    

Private Access Modifier

Private members are only accessible within the class where they are defined. This provides the highest level of encapsulation.


class BankAccount {
    private $balance = 0;

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

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

$account = new BankAccount();
$account->deposit(100);
echo $account->getBalance(); // Outputs: 100
// echo $account->balance; // This would cause an error
    

Protected Access Modifier

Protected members are accessible within the declaring class and all its subclasses. This is useful for implementing inheritance while maintaining some level of encapsulation.


class Animal {
    protected $name;

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

class Dog extends Animal {
    public function bark() {
        echo $this->name . " says Woof!";
    }
}

$dog = new Dog("Buddy");
$dog->bark(); // Outputs: Buddy says Woof!
// echo $dog->name; // This would cause an error
    

Best Practices

  • Use the most restrictive access level that makes sense for a particular member.
  • Prefer private access for properties to enforce encapsulation.
  • Use public methods to provide controlled access to private properties.
  • Consider using protected for members that should be accessible in subclasses.

Related Concepts

To deepen your understanding of PHP object-oriented programming, explore these related topics:

By mastering access modifiers, you'll be able to create more robust and maintainable object-oriented PHP code. Remember that proper use of access modifiers is key to implementing encapsulation effectively in your PHP OOP projects.