继承了一个PHP7项目。以前的开发人员甚至为\ true都对所有标准PHP函数添加了斜线。有什么理由吗?
一些例子:
\array_push($tags, 'master');
if ($result === \true) {}
$year = \date('Y');
切换此选项的php-cs-fixer规则是什么?
答案 0 :(得分:6)
您可以使用斜杠确保使用的是本机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-CS-Fixer文档中所述)。 PHP不需要使用自动加载器来查找函数或常量声明。因此,使用领先的\
,PHP可以使用本机函数,而无需进行其他检查。
您可以使用native_function_invocation
(对于函数)和native_constant_invocation
(对于常量)选项在PHP-CS-Fixer上切换此选项。您可以在以下页面上找到有关这些选项的说明:https://github.com/FriendsOfPHP/PHP-CS-Fixer
答案 1 :(得分:4)
正如其他答案所指出的那样,用\
前缀全局或内置函数和常量可确保它们不会被当前名称空间中的声明所覆盖。具有相同效果的另一种方法是在文件顶部添加use function foo;
和use constant foo;
行。
在大多数情况下,这是不必要的,因为PHP会退回到不存在名称空间本地版本的全局/内置版本,但是在某些情况下,如果PHP事先知道哪个是被使用(请参阅PHP-CS-Fixer中的issue 3048和issue 2739)。
在PHP-CS-Fixer中控制此选项的选项为native_function_invocation
。
答案 2 :(得分:2)
以上答案回答了您的第一部分,至于cs-fixer,选项为:
native_function_invocation
和
native_constant_invocation
答案 3 :(得分:2)
由于命名空间。
添加\
将在全局空间中找到名称。
这里是一个例子:
<?php
namespace Foo;
function time() {
return "my-time";
}
echo time(), " vs", \time();
您将得到如下结果:
my-time vs 1553870392
答案 4 :(得分:2)
它也可能是因为性能。 直接从根名称空间调用时,性能会大大提高。
<?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.025378942489624
答案 5 :(得分:0)
使用\
前缀本机PHP函数将指定global namespace中需要它。
从PHP 7开始,如果使用FQDN调用some native functions,则将其替换为操作码。无论如何,OpCache都是PHP 7的热门话题。
但是绝不是所有本机PHP函数都需要这样做。
对于使用PHPStorm的用户,我建议使用Php Inspections (EA Extended) plugin,它可以检查您的整个项目并为您找到这些优化。