PHP access specifiers are keywords used to define the visibility of a class property or method. The three access specifiers are,
Public - Public properties and methods can be accessed from anywhere.
Private - Private properties and methods can only be accessed within the same class.
Protected - Protected properties and methods can be accessed within the same class and its child classes.
Syntax
<?php
class Car {
public $name;
protected $color;
private $type;
}
$volvo = new Car();
$volvo ->name = 'Volvo'; // OK
$volvo ->color = 'Black'; // ERROR
$volvo ->type = 'Sedan'; // ERROR
Sample Code
<?php
class Car {
public $name;
public $color;
public $type;
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_type($n) { // a private function
$this->type = $n;
}
}
$volvo = new Car();
$mango->set_name('Volvo'); // OK
$mango->set_color('Black'); // ERROR
$mango->set_type('Sedan'); // ERROR
?>
Related Searches to PHP Oops Access Specifiers - PHP Access Modifiers
php oop access modifiersphp oops access specifiersphp access modifiersaccess specifiers in phppublic,private protected in php examplesprivate access modifiers in phpaccess specifiers in oops with exampleaccess specifiers in php with examplesaccess specifiers in oopsaccess modifiers in phpinheritance in php