When should public variables in PHP classes be changed to private or protected for better code design?

Public variables in PHP classes should be changed to private or protected when we want to encapsulate the data and prevent direct access from outside the class. This helps in better code design by promoting data hiding and encapsulation, which are key principles of object-oriented programming. By using private or protected visibility, we can control how the data is accessed and manipulated, leading to more robust and maintainable code.

class MyClass {
    private $privateVar;
    protected $protectedVar;
    
    public function __construct($privateVar, $protectedVar) {
        $this->privateVar = $privateVar;
        $this->protectedVar = $protectedVar;
    }
    
    // Getter and setter methods can be used to access and modify private and protected variables
    public function getPrivateVar() {
        return $this->privateVar;
    }
    
    public function setPrivateVar($value) {
        $this->privateVar = $value;
    }
}