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