How can one use dynamic methods in PHP classes using __call or other techniques?

When using dynamic methods in PHP classes, you can utilize the magic method __call to handle method calls that are not explicitly defined in the class. This allows you to create dynamic methods based on the method name and parameters passed. By using __call, you can implement flexible and dynamic behavior in your classes without explicitly defining every possible method.

class DynamicMethodsExample {
    public function __call($method, $args) {
        if (strpos($method, 'dynamic_') === 0) {
            $dynamicMethod = substr($method, 8); // Remove 'dynamic_' prefix
            if (method_exists($this, $dynamicMethod)) {
                return call_user_func_array([$this, $dynamicMethod], $args);
            }
        }
        throw new \BadMethodCallException("Method $method not found");
    }

    public function dynamic_hello($name) {
        return "Hello, $name!";
    }
}

$instance = new DynamicMethodsExample();
echo $instance->dynamic_hello('John'); // Output: Hello, John!