PHP OOP - Access Modifiers


PHP - Access Modifiers

Buildings and routes may have access controllers that control where they can be accessed.

There are three access fixes:

  • public - a place or way can be reached everywhere. This is the default
  • protected - location or route can be accessed within the classroom and classes taken in that class
  • private - location or route can ONLY be accessed within the classroom

In the following example we have added three different editors to access the three properties (name, color, and weight). Here, if you try to set a name location it will work fine (because the name area is public, and can be accessed everywhere). However, if you try to set the color or weight of the item it will lead to a fatal error (because the color and weight material is protected and confidential):


Example
<?php
class Fruit {
  public $name;
  protected $color;
  private $weight;
}

$mango = new Fruit();
$mango->name = 'Mango'; // OK
$mango->color = 'Yellow'; // ERROR
$mango->weight = '300'; // ERROR
?>

In the following example we have added access editors to two functions. Here, if you are trying to drive a set_color () or set_weight () function it will lead to a fatal error (because both functions are considered secure and confidential), even though all properties are public:


Example
<?php
class Fruit {
  public $name;
  public $color;
  public $weight;

  function set_name($n) {  // a public function (default)
    $this->name = $n;
  }
  protected function set_color($n) { // a protected function
    $this->color = $n;
  }
  private function set_weight($n) { // a private function
    $this->weight = $n;
  }
}

$mango = new Fruit();
$mango->set_name('Mango'); // OK
$mango->set_color('Yellow'); // ERROR
$mango->set_weight('300'); // ERROR
?>