![](/img/trans.png)
[英]PHP: using type hinting (scalar types & return types) for namespaced instances
[英]Can I force PHP 7.1 syntax to require type hinting in return types?
從PHP 7.0起, 可以在函數中設置返回類型。
但是您不能強行使用它,因為該語言不支持void
返回類型,並且通過靜態分析很難知道函數是否會返回與void不同的東西。
在PHP 7.1中,允許使用void
返回類型。 這意味着現在所有函數都可以建立返回類型。
有沒有一種方法可以這樣配置PHP,以便在函數未建立返回類型時發出“語法錯誤”?
例如:
private function foo()
{
$this->dummy();
}
會引發語法錯誤,而與此同時:
private function foo() : void
{
$this->dummy();
}
不會。
您不能在PHP中原生地強制執行此操作,但是可以使用PHPCS(或類似方法)對其進行嗅探。
SlevomatCodingStandard.TypeHints.TypeHintDeclaration
如果方法主體包含帶有值的return,則檢查是否缺少@return和/或本機返回typehint。
您可以通過interfaces變得更接近。
interface testinterface {
public function testfunction() : void;
}
class testclass implements testinterface {
public function testfunction() {
echo 'foo';
}
}
將導致以下錯誤:
致命錯誤:testclass :: testfunction()的聲明必須與testinterface :: testfunction()兼容:void in ...
但是,接口不能防范未在接口內定義的函數,因此您必須在邏輯上確保類聲明實現了接口(可以通過instanceof
運算符實現)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.