How can you access a variable from one class within another class in PHP?

To access a variable from one class within another class in PHP, you can use getter and setter methods in the class that contains the variable you want to access. This way, you can retrieve the variable value from one class and set it in another class. Additionally, you can make the variable public or protected and access it directly if the classes are related in terms of inheritance.

class ClassA {
    private $variable;

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

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

class ClassB {
    public function accessVariableFromClassA(ClassA $classA) {
        $value = $classA->getVariable();
        echo $value;
    }
}

$classA = new ClassA();
$classA->setVariable("Hello from ClassA");

$classB = new ClassB();
$classB->accessVariableFromClassA($classA);