The protected access control modifier
When we declare a property or a method as protected, we can approach it from both the parent and the child classes.
In a previous tutorial, we learned that we can use the public access modifier to allow access to a class’s methods and properties from both inside and outside the class. We also learned that those methods and properties that are private can only be used from inside the class.
In this tutorial, we will learn about a third modifier - the protected modifier, which allows code usage from both inside the class and from its child classes.
The first example demonstrates what might happen when we declare the $model property in the parent as private, but still try to access it from its child class.
What do you think might happen when we try to call a private method or property from outside the class?
Here is the code:
// The parent class
class Car {
//The $model property is private, thus it can be accessed
// only from inside the class
private $model;
//Public setter method
public function setModel($model)
{
$this -> model = $model;
}
}
// The child class
class SportsCar extends Car{
//Tries to get a private property that belongs to the parent
public function hello()
{
return "beep! I am a <i>" . $this -> model . "</i><br />";
}
}
//Create an instance from the child class
$sportsCar1 = new SportsCar();
//Set the class model name
$sportsCar1 -> setModel('Mercedes Benz');
//Get the class model name
echo $sportsCar1 -> hello();
Result:
Notice: Undefined property: SportsCar::$model
We get an error because the hello() method in the child class is trying to approach a private property, $model, that belongs to the parent class.
We can fix the problem by declaring the $model property in the parent as protected, instead of private, because when we declare a property or a method as protected, we can approach it from both the parent and the child classes.
// The parent class
class Car {
//The $model property is now protected, so it can be accessed
// from within the class and its child classes
protected $model;
//Public setter method
public function setModel($model)
{
$this -> model = $model;
}
}
// The child class
class SportsCar extends Car {
//Has no problem to get a protected property that belongs to the parent
public function hello()
{
return "beep! I am a <i>" . $this -> model . "</i><br />";
}
}
//Create an instance from the child class
$sportsCar1 = new SportsCar();
//Set the class model name
$sportsCar1 -> setModel('Mercedes Benz');
//Get the class model name
echo $sportsCar1 -> hello();
Result:
beep! I am a Mercedes Benz
Now it works, because we can access a protected code that belongs to a parent from a child class.