作为程序员一定要保持良好的睡眠,才能好编程

php7新特性有哪些

发布时间:2019-03-06

现在php已经升级到php7了,那么php有哪些打的变化呢?

现在就来说说:


1、标量参数类型声明

declare(strict_types=1); //是否开启严禁模式

function test(array $a){
	return count($a);
}



2、返回类型声明

    

function test(array $a):int{
	return count($a);
}


3、语法糖


$username=$_GET['username']??"no"


4、比较运算符 <=>  太空船操作符(组合比较符)


     1<=>2  如果第一个数小于第二个数 返回 -1  等于返回0 、 大于返回 1


5、命名变量上的使用

     use \helper\ClassA;

     use \helper\ClassB;


    php7 

    use \helper\{ClassA,ClassB}


6、define 定义数组


     php5.6 const 可以定义数组了,

    php7中可以使用define去定义数组了


7、匿名函数

$anonymous_func = function(){return 'function';};

echo $anonymous_func(); // 输出function



8、set_exception_handler() 不再保证收到的一定是 Exception 对象


在 PHP 7 中,很多致命错误以及可恢复的致命错误,都被转换为异常来处理了。 这些异常继承自 Error 类,

此类实现了 Throwable 接口 (所有异常都实现了这个基础接口)。


PHP7进一步方便开发者处理, 让开发者对程序的掌控能力更强. 因为在默认情况下, 

Error会直接导致程序中断, 而PHP7则提供捕获并且处理的能力, 让程序继续执行下去, 为程序员提供更灵活的选择。



9、

匿名类

现在支持通过new class 来实例化一个匿名类,实例如下

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) {
        echo $msg;
    }});var_dump($app->getLogger());




//php7新特性

//标量参数类型声明
function test(array $a){
	return count($a);
}
// echo test(['aa','bb']); 
// echo test(123);


//PHP Fatal error:  Uncaught TypeError: Argument 1 passed to test() must be of the type array, integer given, called in D:\phpStudy\WWW\test\php7.php on line 14 and defined in D:\phpStudy\WWW\test\php7.php:6
//
//
//

function test2($a):int{
	return count($a);
	// return [];
}

//PHP Fatal error:  Uncaught TypeError: Return value of test2() must be of the type integer, array returned in //D:\phpStudy\WWW\test\php7.php:20
//Stack trace:
//#0 D:\phpStudy\WWW\test\php7.php(23): test2(123)

// echo test(['aa','bb']); 
echo test2(123);



//语法糖的写法
echo $_GET['aaa']??'no';



//4.<=> 比较运算符
//就是看两个表达式值的大小,三种关系: = 返回0、< 返回-1、 > 返回 1