Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to code/reference to a PHP callable functions easy to manage for my IDE

When I have to write a reference to a callable function I use the standard syntax of PHP defined as:

A PHP function is passed by its name as a string. Any built-in or user-defined function can be used [... omitted...].

A method of an instantiated object is passed as an array containing an object at index 0 and the method name (aka string) at index 1.

Static class methods can also be passed without instantiating an object of that class by passing the class name (still a string) instead of an object at index 0.

As of PHP 5.2.3, it is also possible to pass (the string) 'ClassName::methodName'.

Apart from common user-defined function, anonymous functions can also be passed to a callback parameter.

All of these ways are not "IDE friendly" for operations like function name refactor or find usage of.

In my answer I propose a solution, but there are other approaches that can be applied, even totally different, that allow to IDE to "find" the invocation of the methods?

like image 330
Ivan Buttinoni Avatar asked Dec 03 '15 12:12

Ivan Buttinoni


People also ask

What is PHP callable function?

The callable keyword is used to force a function argument to be a reference to a function. A callable can be one of the following: An anonymous function. A string containing the name of a function. An array describing a static class method.

How do you call a method in PHP?

To invoke a method on an object, you simply call the object name followed by "->" and then call the method. Since it's a statement, you close it with a semicolon. When you are dealing with objects in PHP, the "->" is almost always used to access that object, whether it's a property or to call a method.

Is PHP a callback?

Callback is a pseudo-type in PHP. With PHP 5.4, Callable type hint has been introduced, which is similar to Callback. When some object is identified as callable, it means that it can be used as a function that can be called. A callable can be a built-in or user defined function or a method inside any class.

What is dynamic function PHP?

In PHP, dynamic calls happens when the call will get at least one of its expression's elements (and sometimes, even all of them) at execution time.


1 Answers

You already are next to the shortest thing you can do

You can perfectly call your anonymous function directly in your function call without using a variable

For instance, you can replace:

$callable=function($param) use ($object){ 
   return $object->myMethod($param); 
}
call_user_func($callable, $param);

by:

call_user_func(function($param) use ($object){ 
   return $object->myMethod($param); 
}, $param);

You will have to wait for arrow functions in future PHP versions, and you should be able to use something like:

call_user_func(fn($a) => $object->myMethod($a), $param);
like image 159
Adam Avatar answered Sep 20 '22 22:09

Adam