php7 void return type not working?

后端 未结 5 983
一个人的身影
一个人的身影 2020-12-06 15:48

I have a problem with return types in php7, specially \"void\".

it works with all other types, int, string, null, bool, class objects.

but when i use void it

相关标签:
5条回答
  • 2020-12-06 16:29

    tl;dr

    Return type void works since PHP 7.1 which is already available.

    Working syntax is:

    <?php
    function procedure(): void
    {
    //  return 'will not work';
    }
    
    echo procedure();
    
    0 讨论(0)
  • 2020-12-06 16:31

    Void return types are for PHP 7.1 (which had not yet been released when you asked this). From the RFC

    Version: 0.2.1
    Date: 2015-02-14 (v0.1, later withdrawn), 2015-10-14 (v0.2, revival)
    Author: Andrea Faulds, ajf@ajf.me
    Status: Implemented (PHP 7.1)

    0 讨论(0)
  • 2020-12-06 16:39

    No there is not, until PHP 7.1. For PHP 7.0, you have to omit the return type completely for void functions/methods.

    function printLn($a) {
        echo "$a\n";
    }
    

    Unfortunately, you then have no type safety for this function/method, and no TypeError will be thrown if you start returning something from it.

    Luckily, PHP 7.1 fixes this:

    Support for a new void return type is added. It requires that a function not return any value.

    This is the correct syntax for PHP 7.1:

    function should_return_nothing(): void {
        return 1; // Fatal error: A void function must not return a value
    }
    

    This was postponed during the proposal that created return type hints:

    We keep the current type options. Past proposals have suggested new types such as void, int, string or scalar; this RFC does not include any new types. Note that it does allow self and parent to be used as return types. ...

    Future Work

    Ideas for future work which are out of the scope of this RFC include:

    • Allow functions to declare that they do not return anything at all (void in Java and C)

    NULL also is not allowed as a return type.

    0 讨论(0)
  • 2020-12-06 16:50

    I've just found the answer here: https://wiki.php.net/rfc/void_return_type

    It will be a feature in PHP 7.1

    0 讨论(0)
  • 2020-12-06 16:53

    Why not just use

       function printLn($a) {
        echo $a;
        return;}
    

    It is the same as void.

    You can even remove the return with just the echo

    0 讨论(0)
提交回复
热议问题