PHP Keywords: callable

23 February 2019 - 11:36pm

Welcome to my series on every PHP keyword and its usage. Today's item: callable.

This keyword can only be used as a type hint or return type, and indicates that it only accepts or returns a value of the following form:

  • A closure / anonymous function
  • A string with the name of an existing function
  • An array containing an object as its first value and the name of a method as its second value
  • An array containing the name of a class as its first value and the name of a static method as its second value

A callable can be run by adding arguments inside brackets to the variable name, e.g. $callable($argument).

Usage

<?php
function runCallable(callable  $callable): callable 
{
    // Runs the passed in function
    $callable("I am a callable");

    return $callable;
}

class SimpleClass
{
    public static function runStatic(string $message)
    {
        echo $message;
    }

    public function run(string $message)
    {
        echo $message;
    }
}

function simpleFunction(string $message)
{
    echo $message;
}

$closure = function(string $message)
{
    echo $message;
};

$function = "simpleFunction";
$method = [new SimpleClass(), "run"];
$staticMethod = [SimpleClass::class, "runStatic"];

runCallable($closure);
runCallable($function);
runCallable($method);
runCallable($staticMethod);