Access modifiers public, private, and protected in PHP

Опубликовано: 13 Май 2026
на канале: PHP Explained
252
4

Access modifiers set the scope of access to class properties and methods by the class objects. There are three types of scopes or access available in PHP.

1. public - this is the default access modifier. Properties and methods declared as public in a class can be accessed from anywhere in the code.

2. protected - properties and methods declared as protected in a class can be accessed from the class where it is declared and the classes derived from this class.

3. private - properties and methods declared as private in a class can be accessed from the class where it is declared.

Let's see an example.
We know that public properties and functions can be accessed from anywhere in the code. We also know that default access specifier is public.
So, property color and function get_color() are considered as public.
As a result, all the properties and methods can be accessed by object car1.
class Car
{
public $model;
$color;

public function get_model_name()
{
return $this-gt;model;
}

function get_color()
{
return $this-gt;color;
}
}
$car1 = new Car("Honda", "Gray");
$car1-gt;model = "Honda";
$car1-gt;color = "Gray";
echo $car1-gt;get_model_name();
echo $car1-gt;get_color();

Let's see another example.
Here property model and function get_color() are declared as protected. As per rules, protected properties and methods can be accessed from the class where it is declared and the classes derived from this class. Hence we cannot access these properties and methods. As a result, we will get a fatal error.
class Car
{
protected $model;
$color;

public function get_model_name()
{
return $this-gt;model;
}

protected function get_color()
{
return $this-gt;color;
}
}
$car1 = new Car("Honda", "Gray");
$car1-gt;model = "Honda";
$car1-gt;color = "Gray";
echo $car1-gt;get_model_name();
echo $car1-gt;get_color();

Here is another example.
Function get_color() is declared as private. As per rules private properties and methods can be accessed from the class where it is declared. Hence the object cannot access this function, although properties are declared as public. As a result, we will get a fatal error.
class Car
{
public $model;
public $color;

public function get_model_name()
{
return $this-gt;model;
}

private function get_color()
{
return $this-gt;color;
}
}
$car1 = new Car("Honda", "Gray");
echo $car1-gt;get_model_name();
echo $car1-gt;get_color();