Version 2.4

Callback Functions

Nette\Utils\Callback is a static class, which contains functions for working with PHP callbacks.

All examples assume the following class alias is defined:

use Nette\Utils\Callback;

check($callable, bool $syntax = false): bool

Checks that $callable can be called as a function. Otherwise throws Nette\InvalidArgumentException. If the $syntax is set to true, the function only verifies that $callable has a valid structure to be used as a callback, but does not verify if the class or method actually exists.

echo Callback::check('trim'); // true
echo Callback::check(['NonExistentClass', 'method']); // false
echo Callback::check(['NonExistentClass', 'method'], true); // true
echo Callback::check(function () {}); // true
echo Callback::check(null); // false

closure($callable): Closure

(or closure($classOrObject, $method): Closure)

Converts PHP callback to object Closure.

$trimmer = Callback::closure('trim');
echo $trimmer(' hello '); // 'hello'

Since PHP 7.1 you should use native Closure::fromCallable.

invoke($callable, …$args): mixed

Calls the $callable, passes the remaining parameters as arguments and returns the returned value.

When is not callable, it throws Nette\InvalidArgumentException unlike call_user_func which only triggers a warning.

$callback = 'trim';
echo Callback::invoke($callback, ' hello '); // 'hello'

Since PHP 7.0 you should use native $callback($arg, ...).

invokeArgs($callable, array $args = []): mixed

Calls the $callable with $args arguments and return its value.

When is not callable, it throws Nette\InvalidArgumentException unlike call_user_func which only triggers a warning.

$callback = 'trim';
echo Callback::invoke($callback, [' hello ']); // 'hello'

Since PHP 7.0 you should use native $callback(...$args).

toString($callable): string

Converts PHP callback to textual form.

echo Callback::toString('trim'); // trim
echo Callback::toString(['MyClass', 'method']); // MyClass::method

toReflection($callable): ReflectionMethod|ReflectionFunction

Returns reflection for method or function used in PHP callback.

isStatic($callable): bool

Checks whether PHP callback is function or static method.

echo Callback::isStatic('trim'); // true
echo Callback::isStatic(['MyClass', 'method']); // true
echo Callback::isStatic([$obj, 'method']); // false
echo Callback::isStatic(function () {}); // false