What is the difference between accessing a protected variable in its class and in an extended class in PHP?

When accessing a protected variable in its class, you can directly access the variable without any issues. However, when accessing the protected variable in an extended class, you need to use getter and setter methods to access and modify the variable since it is not directly accessible due to its protected visibility.

class ParentClass {
    protected $variable = 'Protected Variable';

    public function getVariable() {
        return $this->variable;
    }

    public function setVariable($value) {
        $this->variable = $value;
    }
}

class ChildClass extends ParentClass {
    public function displayVariable() {
        echo $this->getVariable();
    }

    public function updateVariable($value) {
        $this->setVariable($value);
    }
}

$child = new ChildClass();
$child->displayVariable(); // Output: Protected Variable
$child->updateVariable('Updated Variable');
$child->displayVariable(); // Output: Updated Variable