![](/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.