问题描述
你能告诉我这叫什么吗??string
和 string
Could you please tell me how is this called? ?string
and string
使用示例:
public function (?string $parameter1, string $parameter2) {}
我想了解一些关于它们的信息,但我在 PHP 文档和谷歌中都找不到它们.它们有什么区别?
I wanted to learn something about them but I cannot find them in PHP documentation nor in google. What is difference between them?
推荐答案
它被称为 可空类型,在 PHP 7.1 中引入.
It's called a Nullable type, introduced in PHP 7.1.
如果有一个 Nullable 类型(带有 ?
)参数,或者一个相同类型的值,你可以传递一个 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
或指定类型.
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
}
属性类型(自 PHP 7.4 起):
属性的类型可以是可为空的类型.
Property type (as of PHP 7.4) :
The type of a property can be a nullable type.
class Foo
{
private object $foo = null; // ERROR : cannot be null
private ?object $bar = null; // OK : can be null (nullable type)
private object $baz; // OK : uninitialized value
}
另见:
可空联合类型(自 PHP 8.0 起)
从 PHP 8 开始,"?T
表示法被认为是 T|null
">
As of PHP 8, "?T
notation is considered a shorthand for the common case of T|null
"
class Foo
{
private ?object $bar = null; // as of PHP 7.1+
private object|null $baz = null; // as of PHP 8.0
}
错误
如果运行的PHP版本低于PHP 7.1,则抛出语法错误:
Error
In case of the running PHP version is lower than PHP 7.1, a syntax error is thrown:
语法错误,意外的?",需要变量 (T_VARIABLE)
?
操作符应该被删除.
PHP 7.1+
function foo(?int $value) { }
PHP 7.0 或更低
PHP 7.0 or lower
/**
* @var int|null
*/
function foo($value) { }
参考文献
从 PHP 7.1 开始:
参数和返回值的类型声明现在可以通过在类型名称前加上问号来标记为可为空.这表示 NULL 和指定的类型一样,可以作为参数传递,也可以作为值返回.
截至 PHP 7.4:类属性类型声明.
As of PHP 7.4 : Class properties type declarations.
截至 PHP8.0 : 可空联合类型
As of PHP 8.0 : Nullable Union Type
这篇关于PHP7中类型声明前的问号(?string或?int)的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!