What do the question marks do before the types of variables in the parameters?

后端 未结 4 1499
情歌与酒
情歌与酒 2020-12-04 01:35

Could you please tell me how is this called? ?string and string

Usage example:

public function (?string $parameter1, strin         


        
相关标签:
4条回答
  • 2020-12-04 01:58

    That means that the argument is allowed to be passed as the specified type or NULL:

    http://php.net/manual/en/migration71.new-features.php

    0 讨论(0)
  • 2020-12-04 02:03

    This is roughly equivalent to

     public function (string $parameter1 = null, string $parameter2) {}
    

    Except that the argument is still required, and an error will be issued if the argument is omitted.

    Specifically in this context, the second argument is required and using =null would make the first optional, which doesn't really work. Sure it works but what I mean that it does not actually make it optional, which is the main purpose of default values.

    So using

    public function (?string $parameter1, string $parameter2) {}
    

    Syntactically makes a bit more sense in this instance.

    0 讨论(0)
  • 2020-12-04 02:04

    It's called a Nullable type, introduced in PHP 7.1.

    You could pass a NULL value if there is a Nullable type (with ?) parameter, or a value of the same type.

    Parameters :

    function test(?string $parameter1, string $parameter2) {
            var_dump($parameter1, $parameter2);
    }
    
    test("foo","bar");
    test(null,"foo");
    test("foo",null); // Uncaught TypeError: Argument 2 passed to test() must be of the type string, null given,
    

    Return type :

    The return type of a function can also be a nullable type, and allows to return null or the specified type.

    function error_func():int {
        return null ; // Uncaught TypeError: Return value must be of the type integer
    }
    
    function valid_func():?int {
        return null ; // OK
    }
    
    function valid_int_func():?int {
        return 2 ; // OK
    }
    

    From documentation:

    Type declarations for parameters and return values can now be marked as nullable by prefixing the type name with a question mark. This signifies that as well as the specified type, NULL can be passed as an argument, or returned as a value, respectively.

    0 讨论(0)
  • 2020-12-04 02:14

    The question mark before the string in your function parameter denotes a nullable type. In your above example, $parameter1 must is allowed to have a NULL value, whereas $parameter2 is not; it must contain a valid string.

    Parameters with a nullable type do not have a default value. If omitted the value does not default to null and will result in an error:

    function f(?callable $p) { }
    f(); // invalid; function f does not have a default

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