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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?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);