__invoke() on callable Array or String

陌路散爱 提交于 2019-12-02 02:09:16

It’s easy to implement for calling class member:

<?php

function passthrough_invoke(callable $callback) {
    return $callback->__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 :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!