How do I dynamically invoke a class method in PHP?

后端 未结 9 1056
时光取名叫无心
时光取名叫无心 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:27

    This may be useful as a substitute

    class ReferenceContainer {
    
        function __construct(CallbackContainer $callbackContainer) {
    
            //Alternatively you can have no parameters in this constructor and create a new instance of CallbackContainer and invoke the callback in the same manner        
            //var_dump($this->callbackContainer);
            $data = 'This is how you parse a class by reference';
            $callbackContainer->myCallback($data);
    
        }
    
    }
    
    class CallbackContainer {
    
        function __construct() {}
    
        function myCallback($data) {
    
            echo $data."\n";
    
        }
    
    }
    
    $callbackContainer = new CallbackContainer();
    $doItContainer = new ReferenceContainer($callbackContainer);
    

提交回复
热议问题