上手並過渡到PHP7(2)——必須傳遞int, string, bool參數?沒問題


Type hints, Type safe

泊學實操視頻 
泊學原文鏈接
PHP 7中最引人注目的新特性之一,無疑是Scalar type hints。我們可以在函數參數和返回值中使用scalar type hints,還可以指定scalar type的推導和匹配方式。

Scalar type hints

Type hints並不是什么新生事物,PHP 5.0第一次引入了type hints特性,允許我們指定函數的參數是一個特定class或interface類型。之后,在PHP 5.1中,我們可以指定參數是一個array type,在PHP 5.4中,我們可以指定參數是一個“可被調用(callable)”的類型(例如:function或Closure)。在經過了對RFC若干次的修改和討論之后,PHP 7終於把scale type也加入到了type hint中。

PHP 7允許我們在type hints中使用下面這4種scalar type:

bool: true/false;
float: 表示浮點數類型;
int: 表示整數類型;
string: 表示字符串類型;
我們來看一個使用上面這些scalar type hints的例子:

<?php function sendHttpResponse(int $statusCode, string $statusText) { } sendHttpResponse(200, "OK"); sendHttpResponse("404", "File not found"); 

對於上面的兩個調用,是否滿足sendHttpResponse的type hints,取決於我們對匹配方式的設置。

Coercive Type

這是PHP 7針對scalar type hints采取的默認方式,即盡可能嘗試把參數轉換成scalar type hints要求的類型。所以,在sendHttpResponse("404", "File not found")中,"404"會被轉換成整數400,讓函數得以正常執行。當然,方便總是有代價的,因為類型轉換有時會導致精度丟失。我們來看一些常見的例子:

<?php function coerciveInt(int $a) { echo "a = ".$a; } coerciveInt(1.5); // 1 coerciveInt("100.1"); // 100 coerciveInt("100int"); // 100 function coerciveFloat(float $a) { echo "a = ".$a; } coerciveFloat(1); // 1.0 coerciveFloat("3.14"); // 3.14 coerciveFloat("3.14PI"); // 3.14 

在這里,要特別說一下bool類型,它和我們在C++中的處理邏輯類似,一切表達“空值”的概念,例如:0, 0.0, null, "0", ""(空字符串), [](空數組),$uninitializedVar(未經初始化的變量),都會被認為是false,除去這些情況之外的,則會被認為是true。

Strict Type

如果你不希望PHP 7執行上面的類型轉換,要求類型嚴格匹配,你可以手動啟用PHP 7的“嚴格模式”。在這個模式下,任何不嚴格匹配的類型都會導致拋出\TypeError異常。Strict type只能在web application的中使用,也就是說,如果你在編寫一個library,你不能在你的代碼里,開啟strict type。

啟用strict type很簡單,在PHP代碼中的第一行,寫上declare(strict_types=1);。

*“PHP起始標記和declare(strict_types=1);之間,不能有任何內容,namespace必須緊跟在declare語句后面。”
特別提示*

我們來看一些例子,它們都會導致\TypeError異常:

<?php declare(strict_types=1); function strictInt(int $a) { echo "a = ".$a; } strictInt(1.5); // \TypeError strictInt("100.1"); // \TypeError strictInt("100int"); // \TypeError function strictFloat(float $a) { echo "a = ".$a; } strictFloat(1); // \TypeError strictFloat("3.14"); // \TypeError strictFloat("3.14PI"); // \TypeError

Return Type Hints

在PHP 7,我們除了可以type hint函數參數之外,還可以type hint函數的返回值,像下面這樣:

<?php function divisible(int $dividend, int $divider): int { return $dividend / $divider; } divisible(6, 3); divisible(6, 4); 

Return type hints對類型的處理,和參數使用的規則是相同的。默認采用coersive type,當開啟strict type之后,不滿足約定的類型將會導致\TypeError異常。

 

原文:
https://segmentfault.com/a/1190000004150197


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM