php7.0新特性简单介绍

php7.0新特性简单介绍

1.标量类型声明 有两种模式: 强制 (默认) 和 严格模式。支持字符串(string), 整数 (int), 浮点数 (float), 以及布尔值 (bool)。

严格模式:

declare(strict_types=1);

function aa(int $a){

    return $a;

}

echo aa('5');//会报错。


强制模式:

declare(strict_types=0);//默认就是强制

function aa(int $a){

    return $a;

}

echo aa('5');//输出5。



2.返回值类型声明  方法名(参数...) : 返回值类型{}

 function aa(int $a) : array{

    return [$a];

}


3.null合并运算符

由于日常使用中存在大量同时使用三元表达式和 isset()的情况, 我们添加了null合并运算符 (??) 这个语法糖。如果变量存在且值不为NULL, 它就会返回自身的值,否则返回它的第二个操作数。

// if it does not exist.
$username $_GET['user'] ?? 'nobody';
// This is equivalent to:

$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';


4.太空船操作符(组合比较符)

echo $a <=> $b;//当$a>$b 输出1  当$a < $b 输出-1    当$a == $b 输出0


5.通过 define() 定义常量数组

这个比较好,如下所示:

defined('ANIMALS') or define('ANIMALS', [
    'dog',
    'cat',
    'bird'

]);

var_dump(ANIMALS);//输出array(3) { [0]=> string(3) "dog" [1]=> string(3) "cat" [2]=> string(4) "bird" }

6.匿名类

$a = new class{
public function echo(){
return $this;
}
public function className(){
return __CLASS__;
}
};

var_dump($a->className());

//string(67)"class@anonymousF:\WWW\test\test02.php001A0165"


7.Closure::call()  闭包调用

Closure::call() 现在有着更好的性能,简短干练的暂时绑定一个方法到对象上闭包并调用它。

class A{private $x = 1;}


$getx = function(){
return $this -> x;
};


echo $getx->call(new A); //输出1



猜你喜欢

转载自blog.csdn.net/lvqingyao520/article/details/79733627