Sobes.tech
Junior — Middle

What is the role of the 'protected' keyword in defining access modifiers in object-oriented programming?

sobes.tech AI

Answer from AI

The keyword protected in object-oriented programming in PHP denotes an access modifier that restricts the visibility of a class property or method. Class members with the protected modifier are accessible within the class itself and its subclasses, but not from external code.

This allows for encapsulation while still enabling functionality extension in child classes.

Example:

class Base {
    protected $value = 10;

    protected function getValue() {
        return $this->value;
    }
}

class Child extends Base {
    public function showValue() {
        return $this->getValue(); // access to parent's protected method
    }
}

$obj = new Child();
echo $obj->showValue(); // outputs 10
// $obj->getValue(); // will cause an error because the method is protected