i

PHP Tutorial

PHP-Access Modifiers

Access modifiers are used to limit the access of the properties and methods of a class. They control the properties and methods and specify where they can be used or accessed. There are three types of access modifiers in OOP.

1. Public – It is a default access modifier and the properties and methods can be accessed from anywhere in the script.

2. Protected – You can access the properties and methods only within the class or the classes derived from that class where this access modifier is mentioned.

3. Private – It specifies the properties and methods can only be accessed within the class.

class Car {

  public $name;

  protected $color;

  private $price;

}

$Ferrari = new Car();

$Ferrari ->name = Ferrari; // Public property can be accessed outside class, so it works.

$Ferrari->color = 'Red'; // A protected property cannot be accessed outside class, Error

$Ferrari->price = '9000000'; // Private property cannot be accessed outside class, Error

?>