How can the __set and __get magic methods be used to access properties of the main object in PHP classes?

The __set and __get magic methods can be used to access properties of the main object in PHP classes by allowing you to define custom behavior when setting or getting a property that is not accessible directly. By implementing these magic methods in your class, you can control how properties are set and retrieved, enabling you to perform additional logic or validation.

class MyClass {
    private $data = [];

    public function __set($name, $value) {
        $this->data[$name] = $value;
    }

    public function __get($name) {
        return $this->data[$name] ?? null;
    }
}

$obj = new MyClass();
$obj->foo = 'bar';
echo $obj->foo; // Output: bar