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?

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);

I became to a solution, always based on the anonymous-functions that solve the problem but leave me not full satisfied:

Static method of a class

$callable = function($param){ 
    return \my\namespace\myClass::myMethod($param); 
}

method of a object

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

method of $this object

$callable = function($param){ 
    return self::myMethod($param); 
}

Alternatives for oldest php versions

Inside the all classess you gonna call (or in their parents) define the function classname() as follow:

public static function className()
{
    return get_called_class();
}

or for very old PHP:

public static function className()
{
    return "MyClass";
}

Then

call_user_func(array(MyClass::className(), 'myCallbackMethod')); 

Need Your Help

JSF onclick method called two times (without clicking)

jsf primefaces

Here is just one command link with onclick method:

jQuery-driven app. won't work without alert()

javascript jquery ajax alert

I have seen a lot of articles on this, but none dealing with jQuery, so here I go... I am implementing a version of a script from http://javascript-array.com/scripts/jquery_simple_drop_down_menu/ i...