[英]Can I force PHP 7.1 syntax to require type hinting in return types?
From PHP 7.0 it is possible to set the return type in the functions. 从PHP 7.0起, 可以在函数中设置返回类型。
But you cannot force it as the void
return type is not supported by the language and it would be difficult by the static analysis to know if a function will or not return something different from void or not. 但是您不能强行使用它,因为该语言不支持
void
返回类型,并且通过静态分析很难知道函数是否会返回与void不同的东西。
In PHP 7.1 the void
return type is allowed. 在PHP 7.1中,允许使用
void
返回类型。 This means that now all functions could establish a return type. 这意味着现在所有函数都可以建立返回类型。
Is there a way to configure PHP in such a way so it issues a "syntax error" when a function does not have the return type established? 有没有一种方法可以这样配置PHP,以便在函数未建立返回类型时发出“语法错误”?
For example this: 例如:
private function foo()
{
$this->dummy();
}
would throw a syntax error, while this: 会引发语法错误,而与此同时:
private function foo() : void
{
$this->dummy();
}
would not. 不会。
You can't force this natively in PHP but you can use PHPCS (or similar) to sniff for it. 您不能在PHP中原生地强制执行此操作,但是可以使用PHPCS(或类似方法)对其进行嗅探。
The Slevomat Coding Standard sniffs for PHPCS include a check for this: PHPCS的Slevomat编码标准 嗅探对此进行了检查:
SlevomatCodingStandard.TypeHints.TypeHintDeclaration
SlevomatCodingStandard.TypeHints.TypeHintDeclaration
Checks for missing @return and/or native return typehint in case the method body contains return with a value.
如果方法主体包含带有值的return,则检查是否缺少@return和/或本机返回typehint。
You can get closeish with interfaces . 您可以通过interfaces变得更接近。
interface testinterface {
public function testfunction() : void;
}
class testclass implements testinterface {
public function testfunction() {
echo 'foo';
}
}
will cause the following error: 将导致以下错误:
Fatal error: Declaration of testclass::testfunction() must be compatible with testinterface::testfunction(): void in ...
致命错误:testclass :: testfunction()的声明必须与testinterface :: testfunction()兼容:void in ...
However, interfaces don't guard against functions not defined within the interface, and you have to have logic somewhere making sure that the class declaration is implementing the interface (Which can be achieved with the instanceof
operator ). 但是,接口不能防范未在接口内定义的函数,因此您必须在逻辑上确保类声明实现了接口(可以通过
instanceof
运算符实现)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.