The ::class Notation in PHP: A Comprehensive Explanation
The ::class notation in PHP is a relatively recent addition to the language, introduced in version 5.5. This notation allows you to retrieve the fully qualified name of a class, including its namespace.
How to Use ::class
To use the ::class notation, simply write the name of the class followed by the ::class suffix:
SomeClass::class
This will return the full name of the class, such as:
App\Console\Commands\Inspire
Benefits of Using ::class
The ::class notation offers several advantages over traditional methods of storing class names:
use App\Console\Commands\Inspire; //... protected $commands = [ Inspire::class, // Equivalent to "App\Console\Commands\Inspire" ];
Additional Applications of ::class
In addition to its primary function, the ::class notation can also be used for late static binding, a technique where the name of the derived class is resolved inside the parent class. This can be accomplished by using the static::class syntax:
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 Notation and How Does it Simplify Class Handling?. For more information, please follow other related articles on the PHP Chinese website!