本文主要介紹php 8.0特性(php 8中的新特性),下面一起看看php 8.0特性(php 8中的新特性)相關資訊。
1.關節(jié)類型
一個變量可以定義多種數(shù)據(jù)類型。比如以前需要寫一個函數(shù)計算兩個值的相加,分別定義整型和浮點型?,F(xiàn)在,只需要一個函數(shù)。
先前版本:
函數(shù)sumnum(int $numx,int $numy)
{
返回$ numx $ numy}
函數(shù)sumnum(float $numx,float $numy)
{
返回$ numx $ numy
}
php8,可以這樣寫:
函數(shù)sumnum(int|float $numx,int|float $numy)
{
返回$ numx $ numy
}
2.命名參數(shù)
在以前的版本中,函數(shù)的參數(shù)必須在定義函數(shù)時按照參數(shù)的順序傳遞。在php8之后,參數(shù)的順序可以被打亂,但是在調(diào)用函數(shù)時應該添加參數(shù)名,例如:
$worldpos = strops(&;hello world!&;,“世界”);
對于php8,可以這樣寫:
$ world pos = strops(haystack: &; h:“世界”);
或者
$ world pos = strops(needle : &; world &;,haystack: &; hello world!&;);
3.零算子
在過去,要讀取對象的屬性,需要使用if語句來判斷對象是否為空。該語句很麻煩,例如獲取用戶中的產(chǎn)品數(shù)量 的購物車:
$ itemcount = null
if($用戶!== null){
$ cart = $ user-get cart;
如果($推車!== null){
$ item count = $ cart-item count;
}
}
到php8,可以這樣寫:$itemcount = $user?-getcart?-item count;
4、建造師屬性提升
對于一個類的構造函數(shù),必須先定義前一個類的屬性,然后才能將值從構造函數(shù)傳遞給類屬性,這很麻煩。在php8之后,class屬性可以直接在構造函數(shù)中定義。
先前版本
類別人員{
公共字符串$ name
公共int $gend呃;
public function _ _ construct(string $ name,int $gender){
$ this-name = $ name;
$ this-gender = $ gender;
}
}
php8可以這樣寫:
類別人員{
public function _ _ construct(public string $ name,public int $gender){
}
}
5.匹配表達式,類似于switch。
php 7
開關(8.0){
凱斯 8.0 :
$ r:
$ result = 這是我所期望的
打破;
}
echo $ result
php 8
回聲匹配(8.0){
8.0 = 哦不! ,
8.0 = 這是我所期望的,
};
wenku . baidu . com/view/41 fad 345 c 9 aedd 3383 c4 bb 4 cf 7 ec 4 afe 04 a1 b1 f 5 . html
標簽:
功能參數(shù)
了解更多php 8.0特性(php 8中的新特性)相關內(nèi)容請關注本站點。