PHP:: Fully-qualified method literal to string

Viewed 56

Essentially, I seek to pass a static class method to a callback, but do not wish to do so using a hard-coded string, but rather the fully-qualified class method literal. We can do that using classes like so:

$name = NS\FooClass::class;

instead of:

$name = 'NS\FooClass';

which will give us the string of the fully-qualified name of the class. I seek to be able to do something similar for a class method like so:

$name = NS\FooClass::foo_method::method;

instead of:

$name = 'NS\FooClass::foo_method';

It is more manageable and I can use the IDE functionality way better using the literals. Any similar way I can achieve what I want with the class methods without using strings?

1 Answers

There is currently no such mechanism built into the language. It has been suggested - see for instance this discussion from Feb 2020 - but there are more nuances to think about than might be immediately apparent; notably:

  • Should the syntax resolve at run-time and check the existence of the class and the method (::class in most cases doesn't; a bare function like strlen::func would have to because of the way namespaces resolve; an object implementing __callStatic could never be used this way)?
  • Should the result be a string, an array (see below), or a Closure object?

Anyway, that's a topic for elsewhere...

As the manual page on the callable type says, there are two ways to specify a static method for use as a callback:

  • As a string, as in your example 'NS\FooClass::foo_method'
  • As an array where the first part is a class name, and the second part is a the method name: ['NS\FooClass', 'foo_method']

Since only the class name needs to be qualified with namespace information, you can use ::class with the second syntax to get nearly what you wanted:

$callback = [NS\FooClass::class, 'foo_method'];

This allows any decent IDE to spot the reference to the class, and allows you to reference it by an imported or aliased name.

It's worth noting that if the callable type is specified in a parameter or return type declaration or a docblock, some IDEs (e.g. PhpStorm) will "understand" either format as a reference to the method, and include it in features like "find usages" and "go to declaration".

Related