PHP OOP – Access Modifiers
In PHP, there is access modifiers for properties and methods which controls the property and method accessibility or visibility scope.
There are three access modifiers:
- Public (Default) Access Modifier
- Private
- Protected
Public Access Modifier
Public access modifier is default access modifier. And its properties and methods can be accessible from anywhere.
Let us understand by an example –
<?php class Car{ //Public properties and methods can be accessed from anywhere... public $name; public function get_name() { echo "Car name is ". $this->name; } } $car= new Car(); $car->name= "Volkswagen"; $car->get_name(); ?> //OUTPUT Volkswagen
Private Access Modifier
In private access modifier, the properties and methods can only be accessed within the class itself.
For example:
<?php class Car{ public $name; private $price; } $car = new Car(); $car->name = 'Volkswagen'; //OK $car->price= '30,000,00'; //ERROR ?>
Protected Access Modifier
In Protected access modifier, the properties and methods can be accessed within the class and by the classes derived from that class.
For example:
<?php class Car{ public $name; protected $price; } $car = new Car(); $car->name = 'Volkswagen'; //OK $car->price= '30,000,00'; //ERROR ?>