16

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?

Renzo
  • 26,848
  • 5
  • 49
  • 61
Ivan Buttinoni
  • 4,110
  • 1
  • 24
  • 44

2 Answers2

10

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);
Adam
  • 17,838
  • 32
  • 54
2

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')); 
Ivan Buttinoni
  • 4,110
  • 1
  • 24
  • 44