How can private variables be accessed and manipulated in PHP classes that are extended by child classes?

Private variables in PHP classes cannot be accessed directly by child classes. To access and manipulate private variables in a parent class from a child class, you can use getter and setter methods. Getter methods allow child classes to retrieve the value of private variables, while setter methods enable child classes to modify the value of private variables.

class ParentClass {
    private $privateVar;

    public function getPrivateVar() {
        return $this->privateVar;
    }

    public function setPrivateVar($value) {
        $this->privateVar = $value;
    }
}

class ChildClass extends ParentClass {
    public function manipulatePrivateVar() {
        $this->setPrivateVar('New value'); // Set the private variable
        echo $this->getPrivateVar(); // Get and display the private variable
    }
}

$child = new ChildClass();
$child->manipulatePrivateVar();