PHP7 中类型声明之前的问号(?string 或?int)的用途是什么?

2024-04-13

你能告诉我这个怎么称呼吗??string and string

使用示例:

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

我想了解一些关于它们的知识,但我在 PHP 文档和 google 中都找不到它们。他们之间有什么区别?


什么是可空类型?

PHP 7.1 中引入,

现在可以通过在类型名称前面加上问号来将参数和返回值的类型声明标记为可为空。这表示除了指定类型之外,NULL 还可以分别作为参数传递或作为值返回。

在参数中

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 or string参数 :

function acceptOnlyStrings(string ...$parameters) { }
function acceptStringsAndNull(?string ...$parameters) { }

acceptOnlyStrings('foo', null, 'baz'); // Uncaught TypeError: Argument #2 must be of type string, null given
acceptStringsAndNull('foo', null, 'baz'); // OK

返回类型

函数的返回类型也可以是可空类型,并允许返回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 开始)

属性的类型可以是可为空的类型。

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"

class Foo
{
    private ?object $bar = null; // as of PHP 7.1+
    private object|null $baz = null; // as of PHP 8.0
}

Error

如果运行的PHP版本低于PHP 7.1,则会抛出语法错误:

语法错误,意外的“?”,期望变量(T_VARIABLE)

The ?应删除运算符。

PHP 7.1+

function foo(?int $value) { }

PHP 7.0 或更低版本

/** 
 * @var int|null 
 */
function foo($value) { }

参考

As of PHP 7.1:可空类型 https://www.php.net/manual/en/migration71.new-features.php#migration71.new-features.nullable-types :

As of PHP 7.4 https://www.php.net/manual/en/migration74.new-features.php#migration74.new-features.core.typed-properties:类属性类型声明。

As of PHP 8.0 https://www.php.net/manual/en/language.types.declarations.php#language.types.declarations.union.nullable:可为空联合类型

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PHP7 中类型声明之前的问号(?string 或?int)的用途是什么? 的相关文章

随机推荐