Yad*_*ada 6 php php-7 php-cs-fixer
继承了PHP7项目。以前的开发人员甚至为\ true都对所有标准PHP函数添加了斜线。有什么理由吗?
一些例子:
\array_push($tags, 'master');
if ($result === \true) {}
$year = \date('Y');
Run Code Online (Sandbox Code Playgroud)
切换此选项的php-cs-fixer规则是什么?
You can use the slash to make sure you are using the native PHP function or constant and not the function / constant with the same name defined in a namespace of the project.
namespace test;
function array_push($arr, $str) {
return $str;
}
$arr = [];
var_dump(array_push($arr, 'Hello World')); // array_push defined in namespace test
var_dump(\array_push($arr, 'Hello World')); // native array_push function
Run Code Online (Sandbox Code Playgroud)
demo: https://ideone.com/3xoFhm
Another case why you can use the \ slash is to speed up the resolving (as mentioned on the PHP-CS-Fixer documentation). PHP doesn't need to use the autoloader to find the function or constant declaration. So with leading \ PHP can use native function without additional checks.
You can toggle this option on the PHP-CS-Fixer with the native_function_invocation (for functions) and native_constant_invocation (for constants) option. You can find an explanation of the options on the following page: https://github.com/FriendsOfPHP/PHP-CS-Fixer
As other answers have pointed out, prefixing global or built in functions and constants with \ makes sure they are not over-ridden by declarations within the current namespace. An alternative with the same effect is to add use function foo; and use constant foo; lines at the top of your file.
在大多数情况下,这是没有必要的,因为PHP会退回到不存在名称空间本地版本的全局/内置版本,但是在少数情况下,如果PHP事先知道所使用的版本,则会有性能优势(请参阅问题3048和PHP-CS-Fixer中的问题2739)。
在PHP-CS-Fixer中控制此选项为native_function_invocation。