1.2.1315. Use ::Class Operator¶
Use
\:\:classto hardcode class names, instead of strings.
This is actually faster than strings, which are parsed at execution time, while \:\:class is compiled, making it faster to execute.
\:\:class operator is also able to handle use expressions, including aliases and local namespace. The code is easier to maintain. For example, the target class’s namespace may be renamed, without changing the \:\:class, while the string must be updated.
\:\:class operator works with self and ``static``keywords.
This is not possible when building the name of the class with concatenation.
This is a micro-optimization. This also helps static analysis, as it gives more information at compile time to analyse.
<?php
namespace foo\bar;
use foo\bar\X as B;
class X {}
$className = '\foo\bar\X';
$className = foo\bar\X::class;
$className = B\X;
$object = new $className;
?>
See also ::class.
1.2.1315.1. Connex PHP features¶
1.2.1315.1.1. Suggestions¶
Replace strings by the ::class operator whenever possible
1.2.1315.1.2. Specs¶
Short name |
Classes/UseClassOperator |
Rulesets |
|
Exakat since |
0.8.7 |
PHP Version |
All |
Severity |
Minor |
Time To Fix |
Instant (5 mins) |
Precision |
Medium |
Examples |
|
Available in |