PHP7.4 新特性
PHP7.4已經(jīng)發(fā)布了。又帶來(lái)了一些新特性。可以讓我們的代碼寫(xiě)的更少了。
1.屬性添加限定類型
<?php class User { public int $age; public string $name } $user = new User(); $user->age = 10; $user->name = "張三"; //error $user->age = "zhang";//需要傳遞int
2. 箭頭函數(shù)
這個(gè)特性基本上參考 Js 的 ES6 的語(yǔ)法??梢宰屛覀兊拇a寫(xiě)的更少。如果你的代碼有 fn 這個(gè)函數(shù)??赡軙?huì)沖突
<?php $factor = 10; $nums = array_map(fn($n)=>$n * $factor,[1,2,3]);//[10,20,30] //之前的寫(xiě)法 $nums = array_map(function($num)use($factor){ return $num * $factor; },[1,2,3])
3. 有限返回類型協(xié)變與參數(shù)類型逆變
僅當(dāng)使用自動(dòng)加載時(shí),才提供完全協(xié)變 / 逆變支持。在單個(gè)文件中,只能使用非循環(huán)類型引用,因?yàn)樗蓄愒诒灰弥岸急仨毧捎谩?/p>
<?php class A {} class B extends A {} class Producer { public function method(): A {} } class ChildProducer extends Producer { public function method(): B {} } ?>
4. 數(shù)組解包
使用展開(kāi)運(yùn)算符… 解包數(shù)組。這個(gè)特性,應(yīng)該又是從 js 那吸收過(guò)來(lái)的??蠢?/p>
<?php $parts = ['apple', 'pear']; $fruits = ['banana', 'orange', ...$parts, 'watermelon'];//['banana', 'orange', 'apple', 'pear', 'watermelon']; //老的寫(xiě)法 $fruits = array_merge(['banana', 'orange'],$parts,['watermelon']);
5. 空合并運(yùn)算符賦值
<?php $array['key'] ??= computeDefault(); // 老的寫(xiě)法 if (!isset($array['key'])) { $array['key'] = computeDefault(); } ?>
6. 數(shù)值文字分隔符
數(shù)字文字可以在數(shù)字之間包含下劃線。
<?php 6.674_083e-11; // float 299_792_458; // decimal 0xCAFE_F00D; // hexadecimal 0b0101_1111; // binary ?>
7. 允許從 __toString () 拋出異常
現(xiàn)在允許從 __toString() 引發(fā)異常,以往這會(huì)導(dǎo)致致命錯(cuò)誤,字符串轉(zhuǎn)換中現(xiàn)有的可恢復(fù)致命錯(cuò)誤已轉(zhuǎn)換為 Error 異常。
8. Filter
新增 FILTER_VALIDATE_FLOAT
<?php filter_var(1.00,FILTER_VALIDATE_FLOAT); filter.filters.validate
9. strip_tags 支持?jǐn)?shù)組
<?php strip_tags($str,['p','a','div']); //老的寫(xiě)法 strip_tags($str,"<p><a><div>"); 廢棄的特性 1. 沒(méi)有顯式括號(hào)的嵌套三元運(yùn)算符 <?php 1 ? 2 : 3 ? 4 : 5; // deprecated (1 ? 2 : 3) ? 4 : 5; // ok 1 ? 2 : (3 ? 4 : 5); // ok ?>
面試的時(shí)候,終于不用擔(dān)心問(wèn)你這個(gè)結(jié)果是啥了。其實(shí)生產(chǎn)中,大家也不會(huì)這么寫(xiě)。
2. 花括號(hào)訪問(wèn)數(shù)組索引
<?php $arr = ["a"=>"111"]; $index = "a"; $arr{$index}//廢棄 $arr[$index];
說(shuō)實(shí)話,還是第一次見(jiàn)到,廢棄了,說(shuō)明大家不會(huì)這么用。
3. real 和 is_real 實(shí)數(shù)
<?php $num = ""; $a = (real) $num;//廢棄 $a = (float) $num;
4. parent 關(guān)鍵詞在沒(méi)父類的類中使用
在沒(méi)有父類的類中使用 parent 會(huì)出現(xiàn)編譯錯(cuò)誤。
<?php class Test{ public function index() { return parent::index();//編譯錯(cuò)誤 } }
5. money_format 函數(shù)
money_format 被廢棄,使用 numberFormater 替換
6. 移除的拓展
1.Firebird/Interbase 2.Recode 3.WDDX