Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closure overloading: is it possible to inspect the number of arguments a PHP closure has without executing it?

What I want to do

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.

Background information

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.

Please note

  • I am using PHP5.3
  • As a reminder, I do not want to execute the function and thus cannot use func_num_args
like image 274
Will Morgan Avatar asked Mar 07 '12 18:03

Will Morgan


People also ask

Is overloading possible in PHP?

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++.

Why function overloading is not possible in PHP?

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.

What is closure in PHP and why does it use use identifier?

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.

How can we overload a method in PHP?

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.


1 Answers

With Reflection:

$ref = new ReflectionFunction(function($foo, $bar) {});
echo $ref->getNumberOfParameters(); // 2
like image 62
Gordon Avatar answered Dec 18 '22 14:12

Gordon