How can overloading be used in PHP to dynamically generate properties and methods?

Overloading in PHP allows us to dynamically create properties and methods in classes. This can be achieved by using the magic methods __set() and __get() to handle property access and the magic methods __call() and __callStatic() to handle method calls. By implementing these magic methods, we can dynamically generate properties and methods based on the input provided.

class DynamicClass {
    private $data = [];

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

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

    public function __call($method, $args) {
        if (strpos($method, 'get') === 0) {
            $property = lcfirst(substr($method, 3));
            return $this->data[$property];
        }
    }

    public static function __callStatic($method, $args) {
        if (strpos($method, 'create') === 0) {
            $className = ucfirst(substr($method, 6));
            return new $className();
        }
    }
}

// Dynamically setting properties
$obj = new DynamicClass();
$obj->name = 'John';
$obj->age = 30;

echo $obj->name; // Output: John

// Dynamically calling methods
$obj->setCity('New York');
echo $obj->getCity(); // Output: New York

// Dynamically creating objects
$newObj = DynamicClass::createDynamicClass();