Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

PHP Access Modifiers

PHP – Access Modifiers

Properties and methods in PHP can have access modifiers that determine their visibility.

There are three access modifiers:

  • public: The property or method can be accessed from anywhere. This is the default access level.
  • protected: The property or method can be accessed within the class and by classes derived from that class.
  • private: The property or method can only be accessed within the class itself.

In the example below, we have applied three different access modifiers to the properties (name, color, and weight). The name property can be accessed and modified from anywhere because it is public. However, attempting to modify the color or weight properties will result in a fatal error because they are protected and private, respectively.

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, access modifiers have been applied to two functions. Attempting to call the set_color() or set_weight() functions will result in a fatal error because these functions are protected and private, respectively, even though all the 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
?>