正文 1955字数 71,722阅读

php7发布已有半月,最近有时间了解一下php7的新特性,当然,这个版本最大的特点是性能的提升。在下并非高手,欢迎大家指出错误,同时期待共同交流

1.在use语句增加了group支持
use FooLibrary\Bar\Baz\{ ClassA, ClassB, ClassC, ClassD as Fizbo };
Run code
Cut to clipboard


    2.增加??操作符
    isset($_GET['mykey']) ? $_GET['mykey'] : ""笨重 $_GET['mykey'] ?: "" 当mykey不存在时会报一个E_NOTICE $_GET['mykey'] ?? 'defaultvalue' 安全不会报E_NOTICE $username = $_GET['user'] ?? 'nobody';
    Run code
    Cut to clipboard


      3. 64位PHP7字符串长度可以超过2^31次方字节。

      4.增加Closure::call支持
      Closure::call将一个闭包函数动态绑定到一个新的对象实例并调用执行该函数,
      <?php class Value { protected $value; public function __construct($value) { $this->value = $value; } public function getValue() { return $this->value; } } $three = new Value(3); $four = new Value(4); $closure = function ($delta) { var_dump($this->getValue() + $delta); }; $closure->call($three, 4); $closure->call($four, 4); ?> // outputs int(7),int(8)
      Run code
      Cut to clipboard


        5.双引号字符串和heredocs里面支持使用\u{xxxxx}来声明unicode字符。

        6.define对数组的支持
        define('ANIMALS', array( 'dog', 'cat', 'bird' )); echo ANIMALS[1]; // outputs "cat"
        Run code
        Cut to clipboard


          7.增加比较运算符<=>
          $a <=> $b
          如果a等于b则为0
          如果a大于b则为1
          如果a小于b则为-1

          8.php全局保留字可以声明使用
          class View { public function include(View $view) { //... } }
          Run code
          Cut to clipboard

            include关键字可以当普通字符串关键字一样被使用

            9.标量类型(int,float,string,bool)支持
            增加declare(strict_types=1)指令声明是否严格类型校验,
            当在文件头声明declare(strict_types=1)
            declare(strict_types=1); function add(float $a, float $b): float { return $a + $b; } add(1, 2); // float(3)
            Run code
            Cut to clipboard


              以上代码如果不开启declare(strict_types=1)或许declare(strict_types=0),php将自动转换参数和返回值到指定类型,
              开启declare(strict_types=1),如果参数类型不是flaot或许返回类型不是float则抛出错误

              10.增加接口为用户层提供安全方便的随机数生成器。RFC:
              https://wiki.php.net/rfc/easy_userland_csprng
              Run code
              Cut to clipboard
                (后续再议)

                11.增加了yield from 操作符。
                https://wiki.php.net/rfc/generator-delegation
                Run code
                Cut to clipboard
                  (后续再议)

                  知识是我们已知的 也是我们未知的 基于已有的知识之上 我们去发现未知的 由此,知识得到扩充 我们获得的知识越多 未知的知识就会更多 因而,知识扩充永无止境