Skip to main content

PHP OOP Access Modifiers

By SamK
0
0 recommends
Category(s)
Topic(s)

Properties and methods in PHP can have access modifiers to control their visibility. Modifiers are divided into three categories.

  • public: The property or method is accessible from anywhere.(default)
  • protected: The property or method can only be accessed within the class itself and by classes that inherit from it.
  • private: The property or method is restricted to being accessed only within the class it is defined in, ensuring the highest level of encapsulation.

Example 1: Properties

<?php
class Animal {
    public $name;       // Can be accessed and modified from anywhere
    protected $type;    // Can be accessed only within the class and its subclasses
    private $weight;    // Can be accessed only within the class itself
}

$dog = new Animal();
$dog->name = 'Dog';    // Allowed: $name is public
$dog->type = 'Mammal'; // Fatal Error: $type is protected
$dog->weight = '25';   // Fatal Error: $weight is private
?>

Example 2: Methods

In the below example, access modifiers are applied to three methods: set_name(), set_species() and set_Weight().

<?php
class Animal {
  public $name;
  public $species;
  public $weight;

  // A public method, can be called from anywhere
  function set_name($n) {
      $this->name = $n;
  }

  // A protected method, can only be called within the class and its subclasses
  protected function set_species($n) {
      $this->species = $n;
  }

  // A private method, can only be called within the class
  private function set_weight($n) {
      $this->weight = $n;
  }
}

$dog = new Animal();
$dog->set_name('Dog'); // OK: set_name() is public
$dog->set_species('Mammal'); // Fatal Error: set_species() is protected
$dog->set_weight('25');   // Fatal Error: set_weight() is private
?>

Questions & Answers