MS-特性-PHP7

  1. 标量类型声明,返回值类型声明

     declare(strict_types=1);    //开启强制类型模式
     class obj {
         public function sum(int ...$nums):int {
             return array_sum($nums);
         }
     }
    
     $o = new obj;
     var_dump($o->sum(1, 2, 3, 4, 5, 6));  //21
     var_dump($o->sum(1.11, 2));  //Fatal error: Uncaught TypeError: Argument 1 passed to obj::sum() must be of the type integer, float given
    
  2. NULL 合并运算符 ??

     $username = $_GET['user'] ?? 'nobody';  
     // #$username = is_null($_GET['user']) ? 'nobody': $_GET['user'];
    
  3. 太空船操作符 <=>
    比较两个表达式,前者小于后者时,返回-1,相等时返回0, 大于时返回1,区别于strcmp

     echo "abc" <=> "aec"; //-1
    
  4. 定义常量数组

     define("ANIMAL", [
         "cat",
         "dog",
         "elephant"
     ]);
     echo ANIMAL[0]."
    "; //cat
  5. 匿名类

     interface Logger {
         public function log();
     }
    
     class Application {
         private $logger;
         public function setLogger(Logger $logger) {
             $this->logger = $logger;
         }
    
         public function getLogger():Logger {
             return $this->logger;
         }
     }
    
     $app = new Application;
     $app->setLogger(new class implements Logger{
         public function log()
         {
             echo "This is log"."
    "; } }); $app->getLogger()->log();

你可能感兴趣的:(MS-特性-PHP7)