PHP OOP Access Modifiers
Properties and methods can have access modifiers that control where they can be accessed. This is a fundamental part of Encapsulation, ensuring that internal object data is protected from outside interference.
1. The Three Access Modifiers
PHP provides three keywords to set the visibility of class members:
- public: The property or method can be accessed from everywhere. This is the default.
- protected: The property or method can be accessed within the class and by classes derived from that class (children).
- private: The property or method can only be accessed within the class itself.
2. Example: Property Access
Notice what happens when we try to access protected or private properties from outside the class:
<?php
class Fruit {
public $name;
protected $color;
private $weight;
}
$mango = new Fruit();
$mango->name = 'Mango'; // OK
$mango->color = 'Yellow'; // ERROR (Protected)
$mango->weight = '300'; // ERROR (Private)
?>
3. Using Methods to Access Private Data
To interact with private or protected data, we use Getter and Setter methods. This allows us to validate data before saving it.
<?php
class Employee {
private $salary;
// Setter method
public function setSalary($amount) {
if($amount > 0) {
$this->salary = $amount;
}
}
// Getter method
public function getSalary() {
return $this->salary;
}
}
?>
4. Why Use Access Modifiers?
- Security: Prevent accidental or malicious changes to sensitive data.
- Flexibility: You can change the internal implementation of a class without breaking the code that uses it.
- Control: You can make a property "Read-Only" by providing a Getter but no Setter.
Best Practice: A good rule of thumb is to make properties private or protected by default and only make them public if absolutely necessary. Use public methods to interact with them.