HOME HTML EDITOR C JAVA PHP

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:

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?

  1. Security: Prevent accidental or malicious changes to sensitive data.
  2. Flexibility: You can change the internal implementation of a class without breaking the code that uses it.
  3. 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.