callable – PHP Blog http://blog.dev-php.site Snippets and guides Wed, 23 Sep 2020 02:56:08 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.3 Closure vs Callable Type Hinting http://blog.dev-php.site/closure-vs-callable-type-hinting/ Thu, 28 Nov 2019 09:16:26 +0000 http://blog.dev-php.site/?p=169 Continue reading Closure vs Callable Type Hinting]]>
  • function foo(callable $bar) PHP 5.4+
  • function foo(callable $bar = null) PHP 5.4+
  • function foo(): callable PHP 7.0+
  • function foo(): ?callable PHP 7.1+
  • When type hinting, a closure must be an anonymous function, where a callable also can be a normal method/function.

    • Closure is a class and callable is a type.
    • The callable type accepts anything that can be called
    
    function callableFunc(Callable $callback) {
        $callback();
    }
    
    function closureFunc(Closure $closure) {
        $closure();
    }
    
    function anyFunc(Callable $callable) {
        $callable();
    }
    
    function testFunc() {
        echo 'Hello, World!', "
    "; } $testClosure = function(){ echo 'Hello, World!', "
    "; }; // gettype($testClosure); object // var_dump($testClosure); object(Closure)#1 (0) { } try{ closureFunc($testClosure); // Hello, World! callableFunc("testFunc"); // Hello, World! anyFunc($testClosure); // Hello, World! callableFunc($testClosure); // Hello, World! closureFunc("testFunc");// Argument 1 passed to closureFunc() must be an instance of Closure, string given } catch(TypeError $e){ echo $e->getMessage(), "
    "; } finally { echo "Reachable statement"; }
    ]]>