简体   繁体   中英

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.

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.

In PHP 7.1 the void return type is allowed. This means that now all functions could establish a return type.

Question

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?

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.

The Slevomat Coding Standard sniffs for PHPCS include a check for this:

SlevomatCodingStandard.TypeHints.TypeHintDeclaration

Checks for missing @return and/or native return typehint in case the method body contains return with a value.

You can get closeish with 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 ...

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM