美文网首页
MS-特性-PHP7

MS-特性-PHP7

作者: Captain_tu | 来源:发表于2019-01-03 18:38 被阅读1次
    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]."<br>";  //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"."<br>";
           }
       });
      
       $app->getLogger()->log();

    相关文章

      网友评论

          本文标题:MS-特性-PHP7

          本文链接:https://www.haomeiwen.com/subject/wvjqrqtx.html