Being familiar with PHP Access Modifiers

Access modifiers are a useful feature for controlling where properties and methods can be accessed.

There are three access modifiers are available:

public: Anyone can access the property or function from anywhere.

Protected: Means that only members of the class and classes deriving from it can access the property or function.

Private: Means that only members of the class may access the method or property.

Three distinct access modifiers have been introduced to three properties (name, color, and weight) in the example that follows. Since the name property is public and accessible from anywhere, trying to set it here will function properly. Nevertheless, attempting to modify the color or weight attribute will lead to a fatal error since the

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

$mango = new Fruit();

$mango->name = ‘Mango’; // OK
$mango->color = ‘Yellow’; // ERROR
$mango->weight = ‘300’; // ERROR
?>

The following example shows two functions that now have access modifiers. In this case, even if all the attributes are public, calling the set_color() or set_weight() procedures will result in a fatal error since they are regarded as protected and private:
Example

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(‘Apple’); // OK
$mango->set_color(‘Red’); // ERROR
$mango->set_weight(‘500’); // ERROR
?>

I hope this helps make it clear.