I try to explain the use of ::class
.
Magento 2 uses ::class
because it is specified in the framework's coding standard.
The Magento 2 documentation page reference is here : https://devdocs.magento.com/guides/v2.2/coding-standards/code-standard-php.html
Class name resolution standard
For class name resolution, use the ::class
keyword instead of a string
literal for every class name reference outside of that class. This
includes references to:
Fully qualified class name
Imported/non-imported class name
Namespace relative class name
Import relative class name
Some other useful StackOverflow answers provide justification for this:
https://stackoverflow.com/questions/30770148/what-is-class-in-php
It's very useful for 2 reasons.
You don't have to store your class names in strings anymore. So, many IDEs can retrieve these class names when you refactor your code
You can use the use
keyword to resolve your class and you don't need to write the full class name.
This feature is also useful for Late Static Binding.
Instead of using the __CLASS__
magic constant, you can use the
static::class
feature to get the name of the derived class inside the
parent class.
Then the PHP RFP explain a little bit more about the why the syntax was introduced: https://wiki.php.net/rfc/class_name_scalars
The ClassName::class
syntax was chosen because it can not clash with
existing constants (as class is a keyword). The feature addition thus
is fully backwards compatible.
And:
Class names in strings have to be fully qualified in PHP. It is not
possible to utilize aliases registered through use statements:
use A\Namespaced\ClassName;
// this will try to create a mock of the global class ClassName, not
// of the aliased class A\Namespaced\ClassName
$mock = $this->getMock('ClassName');
ClassName::class
allows the programmer to easily obtain the fully
qualified class name from an aliased name:
use A\Namespaced\ClassName;
// ClassName::class resolves to 'A\Namespaced\ClassName'
$mock = $this->getMock(ClassName::class);