Leo Galleguillos
Leo Galleguillos

Reputation: 2730

Is it better to use ::class rather than hardcoded string?

In php7, when retrieving instances from dependency injection containers or service containers, is it better to use ::class rather than a hardcoded string? If so, why?

For example, are the following lines preferable:

$diContainer->get(Namespace\SubNamespace\Class::class);
$serviceContainer->get(Namespace\SubNamespace\Class::class);

rather than the following:

$diContainer->get('Namespace\SubNamespace\Class');
$serviceContainer->get('Namespace\SubNamespace\Class');

I've been using hardcoded strings with the belief that the code will compile quicker since php does not need to interpret the ::class keyword. However, I've also seen lots of new php7 code that uses ::class.

More broadly, whenever the fully qualified class name is required, is it generally better to use ::class rather than the hardcoded string?

Upvotes: 0

Views: 101

Answers (1)

deceze
deceze

Reputation: 522109

Using ::class allows you to go from an aliased name to a fully qualified name easily. For example:

use MyNamespace\SubNamespace\Foo\Bar\Baz;

$container->get(Baz::class);

It's a convenience so you don't have to repeat a full class name of something you've already abbreviated. The result is a string either way. Arguably it also makes code less error prone in case you rename classes or namespaces, since in the example above you only have to change the name once, not multiple times. Performance should be the least of your concern, you're likely unable to even measure the performance impact in any real world scenario.

As a general rule of thumb, I'd try to avoid hardcoded strings wherever possible, simply because they are a meaningless opaque blob and neither PHP nor any IDE or other tools can do any sort of static type checking with them or help you in any other way.

Upvotes: 3

Related Questions