What are the best practices for defining and accessing class properties in PHP?

When defining and accessing class properties in PHP, it is best practice to use visibility keywords (public, protected, private) to control access to the properties. Public properties can be accessed from outside the class, protected properties can only be accessed within the class and its subclasses, and private properties can only be accessed within the class itself. This helps to enforce encapsulation and maintain the integrity of the class.

class MyClass {
    public $publicProperty;
    protected $protectedProperty;
    private $privateProperty;

    public function __construct($public, $protected, $private) {
        $this->publicProperty = $public;
        $this->protectedProperty = $protected;
        $this->privateProperty = $private;
    }

    public function getProtectedProperty() {
        return $this->protectedProperty;
    }

    public function setPrivateProperty($value) {
        $this->privateProperty = $value;
    }
}

$obj = new MyClass('public value', 'protected value', 'private value');
echo $obj->publicProperty; // Output: public value
echo $obj->getProtectedProperty(); // Output: protected value
$obj->setPrivateProperty('new private value');