How can you ensure proper encapsulation and access control when working with class variables in PHP?

To ensure proper encapsulation and access control when working with class variables in PHP, you can use access modifiers like private, protected, and public. By declaring class variables as private or protected, you restrict direct access to them from outside the class, promoting encapsulation. You can provide getter and setter methods within the class to allow controlled access to these variables.

class MyClass {
    private $privateVar;

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

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

$obj = new MyClass();
$obj->setPrivateVar("Hello");
echo $obj->getPrivateVar(); // Output: Hello