-->

PHP资讯

您的当前位置:首页 > 资讯 > PHP基础

php7新特性2

2021-04-06 13:45:57  来源:admin 点击:450

空合并运算符
在PHP 7中,引入了一个新的特性,即空合并运算符(??)。它用来替代与isset()函数结合的三元操作。该空如果它存在,而不是空合并运算符返回第一个操作数; 否则返回第二个操作数。

<?php
   // fetch the value of $_GET['user'] and returns 'not passed'
   // if username is not passed
   $username = $_GET['username'] ?? 'not passed';
   print($username);
   print("<br/>");

   // Equivalent code using ternary operator
   $username = isset($_GET['username']) ? $_GET['username'] : 'not passed';
   print($username);
   print("<br/>");
   // Chaining ?? operation
   $username = $_GET['username'] ?? $_POST['username'] ?? 'not passed';
   print($username);

   // output
   //not passed
?>

飞船运算符
它用来比较两个表达式。当第一个表达式分别小于,等于或大于第二个表达式时,它返回-1,0或1。字符串比较ASCII

//integer comparison
   print1 <=> 1);print("<br/>");
   print1 <=> 2);print("<br/>");
   print2 <=> 1);print("<br/>");

// output
    0
    -1
    1

常量数组
使用define()函数定义数组常量。在PHP 5.6中,只能使用const关键字来定义它们。

<?php
//define a array using define function
   define('animals', [
      'dog',
      'cat',
      'bird'
   ]);
   print(animals[1]);
// output
    cat  
?>

匿名类
现在可以使用新类来定义匿名类。匿名类可以用来代替完整的类定义。


<?php
   interface Logger {
      public function log(string $msg);
   }

   class Application {
      private $logger;

      public function getLogger()Logger {
         return $this->logger;
      }

      public function setLogger(Logger $logger) {
         $this->logger = $logger;
      }  
   }

   $app = new Application;
   $app->setLogger(new class implements Logger {
      public function log(string $msg) {
         print($msg);
      }
   });

   $app->getLogger()->log("My first Log Message");
?>

//output

My first Log Message


Closure类
Closure :: call()方法被添加为一个简短的方式来临时绑定一个对象作用域到一个闭包并调用它。与PHP5的bindTo相比,它的性能要快得多。
在PHP 7之前

<?php
   class A {
      private $x = 1;
   }

   // Define a closure Pre PHP 7 code
   $getValue = function() {
      return $this->x;
   };

   // Bind a clousure
   $value = $getValue->bindTo(new A, 'A');

   print($value());
   //output
   1
?>


PHP 7+


<?php
   class A {
      private $x = 1;
   }

   // PHP 7+ code, Define
   $value = function() {
      return $this->x;
   };

   print($value->call(new A));
   //output
   1
?>


相关文章更多 >

© 2024版权所有 水水网

电话:171780793