问号在参数中的变量类型之前做什么? [英] What do the question marks do before the types of variables in the parameters?

查看:137
本文介绍了问号在参数中的变量类型之前做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

能告诉我这叫什么吗? ?stringstring

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

用法示例:

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

我想了解一些有关它们的信息,但是我无法在PHP文档或google中找到它们.它们之间有什么区别?

I wanted to learn something about them but I cannot find them in PHP documentation nor in google. What is difference between them?

推荐答案

它称为

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

如果有可空类型(带有?)参数或相同类型的值,则可以传递NULL值.

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

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,

返回类型:

函数的返回类型也可以是可为null的类型,并允许返回null或指定的类型.

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
}

来自文档:

现在,可以通过在类型名称前加上问号来将

用于参数和返回值的类型声明标记为可为空.这表示与指定的类型一样,NULL可以分别作为参数传递或作为值返回.

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.

这篇关于问号在参数中的变量类型之前做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆