How do I dynamically invoke a class method in PHP?

后端 未结 9 1028
时光取名叫无心
时光取名叫无心 2020-12-08 01:52

How can I dynamically invoke a class method in PHP? The class method is not static. It appears that

call_user_func(...)

only works with st

9条回答
  •  失恋的感觉
    2020-12-08 02:31

    As of PHP7, you use an array-like way:

    // Static call only
    [TestClass::class, $methodName](...$args);
    
    // Dynamic call, static or non-static doesn't matter
    $instance = new TestClass;
    [$instance, $methodName](...$args);
    

    Just replace the class name with TestClass, the method name with $methodName and the method arguments with ...$args. Note that, in the later case, it doesn't matter that the method is static or non-static; PHP will call it automatically.

提交回复
热议问题