What is the ::class
notation in PHP?
A quick Google search returns nothing because of the nature of the syntax.
colon colon class
What's the advantage of using this notation?
protected $commands = [
\App\Console\Commands\Inspire::class,
];
This feature was implemented in PHP 5.5.
Documentation : http://php.net/manual/en/migration55.new-features.php#migration55.new-features.class-name
It's very useful for 2 reasons.
use
keyword to resolve your class and you don't need to write the full class name.For exemple :
use \App\Console\Commands\Inspire;
//...
protected $commands = [
Inspire::class, // Equivalent to "App\Console\Commands\Inspire"
];
Update :
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. For 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