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

后端 未结 4 1513
情歌与酒
情歌与酒 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 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.

提交回复
热议问题