继承了一个PHP7项目。前面的开发人员在所有标准PHP函数中添加了一个斜杠,即使是\true。有什么理由这么做吗?
下面是一些例子:
\array_push($tags, 'master');
if ($result === \true) {}
$year = \date('Y');什么是php补丁规则来切换这个选项?
发布于 2019-03-29 14:42:49
发布于 2019-03-29 14:34:13
可以使用斜杠来确保使用的是本机PHP函数或常量,而不是项目名称空间中同名的函数/常量。
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另一个可以使用\斜杠的例子是加速解析(如PHP文档中提到的)。PHP不需要使用自动加载程序来查找函数或常量声明。因此,使用前面的\,PHP可以使用本机函数而不需要额外的检查。
您可以在PHP和native_function_invocation (用于函数)和native_constant_invocation (用于常量)选项上切换此选项。您可以在下面的页面中找到对这些选项的解释:https://github.com/FriendsOfPHP/PHP-CS-Fixer
发布于 2019-03-29 14:43:24
这也可能是因为业绩。直接从根命名空间调用它时,性能要快得多。
<?php
namespace App;
class Test
{
public function test()
{
$first = microtime(true);
for ($i = 0; $i <= 5000; $i++) {
echo number_format($i).PHP_EOL;
}
echo microtime(true) - $first;
}
public function testNative()
{
$first = microtime(true);
for ($i = 0; $i <= 5000; $i++) {
echo \number_format($i).PHP_EOL;
}
echo microtime(true) - $first;
}
}
$t = new Test();
$t->test();
//0.03601598739624
$t->testNative();
//0.025378942489624https://stackoverflow.com/questions/55419673
复制相似问题