Oihana PHP

countCallableParam.php

Table of Contents

Functions

countCallableParam()  : int
Returns the number of parameters of a given callable.

Functions

countCallableParam()

Returns the number of parameters of a given callable.

countCallableParam(callable|string|array<int, object|string>|object $callable[, bool $useCache = true ]) : int

This function accepts any PHP callable (Closure, invokable object, array [object/class, method], string function name, or static method string) and returns the number of parameters it declares.

Optionally, a cache can be used to avoid repeated reflection lookups for the same callable, which is useful when the callable is repeatedly inspected (e.g., in loops or recursive functions).

The cache never relies on the identifier of an object, which PHP hands to the next object once the first is freed — a new closure would otherwise inherit the count of an old one. A closure is kept in a WeakMap, whose entry goes with the closure ; any other callable is kept under its name — the function, or Class::method (Class::__invoke for an invokable object), since the count belongs to the method, not to an instance.

Parameters
$callable : callable|string|array<int, object|string>|object

The callable to inspect.

$useCache : bool = true

Whether to cache the computed parameter count. Default true.

Tags
throws
InvalidArgumentException

If the callable cannot be resolved or is unsupported.

ReflectionException

If the callable cannot be reflected (rare).

example

Basic usage with a named function

function testFunction($a, $b, $c) }
echo countCallableParam('testFunction'); // 3

With a Closure

$fn = function($x, $y) };
echo countCallableParam($fn); // 2

With an invokable object

class MyCallable { public function __invoke($a, $b, $c, $d) } }
$obj = new MyCallable();
echo countCallableParam($obj); // 4

With a static method

class MyClass { public static function myMethod($x, $y) } }
echo countCallableParam('MyClass::myMethod'); // 2

With an object method

class MyClass { public function myMethod($x, $y, $z) } }
$obj = new MyClass();
echo countCallableParam([$obj, 'myMethod']); // 3
author

Marc Alcaraz (ekameleon)

since
1.0.8
Return values
int —

The number of parameters declared by the callable.

On this page

Search results