mercredi 17 février 2021

PHP reflection: Is there an equivalent for ::class for a method of a class?

In PHP it is possible to get a full class name via class name resolution like this:

Example:

namespace Name\Space;
class ClassName {}

echo ClassName::class;

Output: Name\Space\ClassName

This is better then using a string Name\Space\ClassName directly in the code because code introspection especially in IDEs can find an error directly.

I wonder if there is something similar for methods of a class - this would be specifically useful for callback functions.

This is how you can basically can pass a callback:

$a = function($callback,$arg) { return $callback($arg); }

$a('getInfo',5);

Instead of passing a string here (which might change) I would prefer to do something like this:

$a(MyClass::class::getInfo,5);

With I "go to declaration" click in the IDE I could go directly to getInfo plus I see errors in case with method does not exist anymore. Is there a way to achieve what I want to do here?





Aucun commentaire:

Enregistrer un commentaire