Closurecallable Type Hint 差異


  • Two functions

    function testClosure(Closure $closure)
    {
    $closure();
    }

    function testCallable(callable $callable)
    {
    $callable();
    }
  • Use normal function

    function foo()
    {
    echo 'bar';
    }

    testClosure('foo');
    // PHP Fatal error: Uncaught TypeError:
    // Argument 1 passed to testClosure() must be an instance of Closure, string given

    testCallable('foo');
    // bar
  • Use anonymous function

    testClosure(function () {
    echo 'baz';
    });
    // baz

    testCallable(function () {
    echo 'baz';
    });
    // baz

差別在於 Closure 只能用在匿名函式,callable 則是兩者都可。

References


2018-12-09