Functional PHP provides several helpers to invoke callbacks on values or call methods on objects/collections:
with(mixed $value, callable $callback, bool $invokeValue = true, mixed $default = null): Invokes a callback on $value only if $value is not null. Returns the callback's result or $default (defaults to null) if $value is null.invoke_if(mixed $object, string $methodName, array $methodArguments = [], mixed $defaultValue = null): Invokes $methodName on $object if it is an object and the method is public. Otherwise, returns $defaultValue.invoke(array|Traversable $collection, string $methodName, array $methodArguments = []): Invokes $methodName on every object in the $collection and returns an array of results.invoke_first(array|Traversable $collection, string $methodName, array $methodArguments = []): Invokes $methodName on the first object in the collection that actually contains that method.invoke_last(array|Traversable $collection, string $methodName, array $methodArguments = []): Invokes $methodName on the last object in the collection that actually contains that method.invoker(string $method, array $methodArguments = []): Returns a new callable that, when called with an object, invokes $method on that object with the pre-defined $methodArguments.
use function Functional\with;
use function Functional\invoke_if;
use function Functional\invoke;
use function Functional\invoke_first;
use function Functional\invoke_last;
use function Functional\invoker;
// with()
$retval = with(create_user('John Doe'), function ($user) {
send_welcome_email($user);
return 'my_result';
});
// invoke_if()
$userId = invoke_if($user, 'getId', [], 0);
// invoke()
invoke($meetings, 'addAttendee', $user);
// invoke_first() & invoke_last()
invoke_first($meetings, 'delayEvent', [30]);
invoke_last($meetings, 'changeRoom', ['Room 3']);
// invoker()
$setLocationToMunich = invoker('updateLocation', ['Munich', 'Germany']);
$setLocationToMunich($user);