什么是可空类型?
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:可为空联合类型