Properties and methods in PHP can have access modifiers that determine their visibility.
There are three access modifiers:
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.
<?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.
<?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 ?> |