- 標量類型聲明
function setAge(int $age) {
var_dump($age);
}
// 要求傳入?yún)?shù)是整型
// echo setAge('dwdw');
// Fatal error: Uncaught TypeError: Argument 1 passed to setAge() must be of the type integer, string given...
// 注意這么寫不會報錯
echo setAge('1');
- 返回值類型聲明
class User {}
function getUser() : array {
return new User;
}
// Fatal error: Uncaught TypeError: Return value of getUser() must be of the type array, object returned
var_dump(getUser());
// 改成下面不會報錯
function getUser() : User {
return new User;
}
// 如果返回的類型不對
function getUser() : User {
return [];
}
// 會報
// Fatal error: Uncaught TypeError: Return value of getUser() must be an instance of User, array returned
// 再來個interface的例子, 執(zhí)行下面的不會報錯
interface SomeInterFace {
public function getUser() : User;
}
class User {}
class SomeClass implements SomeInterFace {
public function getUser() : User {
return [];
}
}
// 但是當調用的時候才會檢查返回類型
// Fatal error: Uncaught TypeError: Return value of SomeClass::getUser() must be an instance of User, array returned
(new SomeClass)->getUser();
- 太空船操作符(組合比較符)
太空船操作符用于比較兩個表達式黔姜。當$a小于、等于或大于$b時它分別返回-1蒂萎、0或1
// Integers
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1
// 在usort自定義排序方法中很好用
$arr = ['c', 'd', 'b', 'a'];
// ['a', 'b', 'c', 'd']
usort($arr, function($a, $b) {
return $a <=> $b;
});
- Null合并運算符
PHP7之前:
isset($_GET['id']) ? $_GET['id'] : 'err';
PHP7之后:
$_GET['id'] ?? 'err';
- use 批量聲明
PHP7之前:
use App\Model\User;
use App\Model\Cart;
use App\Model\Base\BaseUser;
PHP7之后:
use App\Model\{
User,
Cart,
Base\BaseUser
};
- 匿名類
class SomeClass {}
interface SomeInterface {}
trait SomeTrait {}
var_dump(new class(10) extends SomeClass implements SomeInterface {
private $num;
public function __construct($num)
{
$this->num = $num;
}
use SomeTrait;
});
// 輸出
object(class@anonymous)[1]
private 'num' => int 10
7.2 之后要注意的地方
- each 函數(shù) 在php7.2已經(jīng)設定為過時
<?php
$b = array();
each($b);
// Deprecated: The each() function is deprecated. This message will be suppressed on further calls
兼容方法
function fun_adm_each(&$array){
$res = array();
$key = key($array);
if($key !== null){
next($array);
$res[1] = $res['value'] = $array[$key];
$res[0] = $res['key'] = $key;
}else{
$res = false;
}
return $res;
}
- count 函數(shù)在php7.2將嚴格執(zhí)行類型區(qū)分. 不正確的類型傳入, 會引發(fā)一段警告.
count方法使用非常廣泛秆吵,升級7.2后多注意測試。
<?php
count('');
// Warning: count(): Parameter must be an array or an object that implements Countable
兼容方法
function fun_adm_count($array_or_countable,$mode = COUNT_NORMAL){
if(is_array($array_or_countable) || is_object($array_or_countable)){
return count($array_or_countable, $mode);
}else{
return 0;
}
}
- create_function創(chuàng)建匿名方法不鼓勵使用五慈。
參考:
https://laracasts.com/series/php7-up-and-running
http://php.net/manual/zh/language.oop5.anonymous.php
https://www.cnblogs.com/phpnew/p/7991572.html