代码之家  ›  专栏  ›  技术社区  ›  Yada

php7向所有标准php函数php cs fixer规则添加斜线

  •  3
  • Yada  · 技术社区  · 6 年前

    继承了一个PHP7项目。前一个开发人员为所有标准的PHP函数添加了一个斜线,即使对于\true也是如此。有什么理由这样做吗?

    一些例子:

    \array_push($tags, 'master');
    
    if ($result === \true) {}
    
    $year = \date('Y');
    

    切换此选项的php cs fixer规则是什么?

    5 回复  |  直到 6 年前
        1
  •  4
  •   IMSoP    6 年前

    正如其他答案所指出的,用 \ 确保它们不会被当前命名空间中的声明覆盖。同样效果的另一种选择是增加 use function foo; use constant foo; 文件顶部的行。

    在大多数情况下,这是不必要的,因为PHP将返回到不存在命名空间本地版本的全局/内置版本,但在某些情况下,如果PHP事先知道正在使用哪个版本,则会有性能优势(请参见 issue 3048 issue 2739 在php-cs-fixer中)。

    在php-cs-fixer中控制它的选项是 native_function_invocation .

        2
  •  6
  •   Sebastian Brosch Navjyot    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
    

    演示: https://ideone.com/3xoFhm

    另一个例子,为什么你可以使用 \ 斜线是为了加快解决速度(如php cs fixer文档中所述)。PHP不需要使用自动加载程序来查找函数或常量声明。所以有了领导 \ PHP可以使用本机函数而无需进行额外的检查。


    您可以使用 native_function_invocation (用于功能)和 native_constant_invocation (对于常量)选项。您可以在以下页面上找到选项的解释: https://github.com/FriendsOfPHP/PHP-CS-Fixer

        3
  •  2
  •   Lulceltech    6 年前

    以上答案回答了您的第一部分,对于CS Fixer,选项如下:

    native_function_invocation
    

    native_constant_invocation
    
        4
  •  2
  •   StevenTan    6 年前

    因为命名空间。

    添加 \ 将从全局空间中查找名称。

    下面是一个例子:

    <?php
    
    namespace Foo;
    
    function time() {
        return "my-time";
    }
    
    echo time(), " vs", \time();
    

    你会得到这样的结果。

    my-time vs 1553870392
    
        5
  •  2
  •   Daan    6 年前

    也可能是因为性能。 当直接从根命名空间调用它时,性能要快得多。

    <?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
    
        6
  •  0
  •   Yes Barry    6 年前

    使用 \ 将指定需要从 global namespace .

    从php 7开始, some native functions 如果使用fqdn调用操作码,则替换为操作码。无论如何,当涉及到php 7时,opcache是一个热门话题。

    但是,所有本机PHP函数都不需要这样做。

    对于使用phpstorm的人,我推荐 Php Inspections (EA Extended) plugin 它可以检查整个项目并为您找到这些优化。