__invoke() on callable Array or String

后端 未结 1 1501
旧时难觅i
旧时难觅i 2021-01-22 08:37

How would one write PHP code to call all \"Callables\" with __invoke()?

The desire here is pass by reference, which is deprecated with call_user_func[

1条回答
  •  情话喂你
    2021-01-22 09:23

    It’s easy to implement for calling class member:

    __invoke();
    }
    
    function passthrough_user(callable $callback) {
        return call_user_func($callback);
    }
    
    function test_func() { return "func_string\n"; };
    
    class test_obj {
        public function test_method() {
            return "obj_method\n";
        }
    }
    
    class CallableWrapper {
        private $inst, $meth;
        public function __construct( $inst, $meth ) {
          $this->inst = $inst;
          $this->meth = $meth;
        }
        public function __invoke() {
            echo $this->inst->{$this->meth}();
        }
    }
    
    print_r("Call User Func Works:\n");
    echo passthrough_user(function() { return "func_closure\n"; });
    echo passthrough_user(array(new test_obj, 'test_method'));
    echo passthrough_user('test_func');
    
    print_r("\n__invoke rocks:\n");
    echo passthrough_invoke( function() { return "func_closure\n"; } );
    echo passthrough_invoke( 
      new CallableWrapper( new test_obj, 'test_method' ) 
    );
    
    // ⇒
    // __invoke rocks:
    // func_closure
    // obj_method
    

    For global scoped function is should be doable as well, but I reject to try to implement wrong patterns :)

    0 讨论(0)
提交回复
热议问题