Understanding ::class in PHP
The ::class syntax in PHP refers to a relatively recent addition introduced in version 5.5. It serves as a shorthand notation to represent the fully qualified name of a class, including its namespace.
Functionality and Advantages
SomeClass::class will return the string representation of SomeClass's fully qualified name. This feature offers several advantages:
use \App\Console\Commands\Inspire; //... protected $commands = [ Inspire::class, // Equivalent to "App\Console\Commands\Inspire" ];
Additional Benefit: Late Static Binding
In addition to the aforementioned advantages, ::class is also useful for implementing Late Static Binding, where the name of the derived class can be obtained within the parent class. This is achieved by using static::class instead of the CLASS magic constant, as seen in the following example:
class A { public function getClassName(){ return __CLASS__; } public function getRealClassName() { return static::class; } } class B extends A {} $a = new A; $b = new B; echo $a->getClassName(); // A echo $a->getRealClassName(); // A echo $b->getClassName(); // A echo $b->getRealClassName(); // B
The above is the detailed content of What is the PHP `::class` Syntax and How Does it Improve Code?. For more information, please follow other related articles on the PHP Chinese website!