I want to inspect a closure (passed as a variable) to determine how many arguments it expects. Essentially, I want to overload a closure in the traditional sense, only by treating it differently.
function someMethod(Closure $callback) {
$varA;
$varB;
$varC;
if($callback->getNumArgs() == 3) {
$callback($varA, $varB, $varC);
}
else {
$callback($varC, $varA);
}
}
If this could be explained better, please let me know so it can be edited.
Depending on how many arguments the closure takes, I will adjust the way in which it's called. I need to do this to save expensive iterations through a loop.
func_num_args
PHP does not support method overloading. In case you've never heard of method overloading, it means that the language can pick a method based on which parameters you're using to call it. This is possible in many other programming languages like Java, C++.
You cannot overload PHP functions. Function signatures are based only on their names and do not include argument lists, so you cannot have two functions with the same name. Class method overloading is different in PHP than in many other languages.
A closure is a separate namespace, normally, you can not access variables defined outside of this namespace. There comes the use keyword: use allows you to access (use) the succeeding variables inside the closure.
To achieve method overloading in PHP, we have to utilize PHP's magic methods __call() to achieve method overloading. __call(): In PHP, If a class executes __call(), and if an object of that class is called with a method that doesn't exist then, __call() is called instead of that method.
With Reflection:
$ref = new ReflectionFunction(function($foo, $bar) {});
echo $ref->getNumberOfParameters(); // 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With