你能告诉我这是怎么回事吗??string和string
用法示例:
public function (?string $parameter1, string $parameter2) {}
Run Code Online (Sandbox Code Playgroud)
我想学习一些关于它们但我无法在PHP文档或谷歌中找到它们.他们之间有什么区别?
Sys*_*all 20
它被称为Nullable 类型,在 PHP 7.1 中引入。
NULL如果有一个 Nullable 类型(带?)参数,或者一个相同类型的值,你可以传递一个值。
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,
Run Code Online (Sandbox Code Playgroud)
函数的返回类型也可以是可空类型,并允许返回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
}
Run Code Online (Sandbox Code Playgroud)
属性的类型可以是可为空的类型。
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
}
Run Code Online (Sandbox Code Playgroud)
也可以看看 :
可空联合类型(自 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
}
Run Code Online (Sandbox Code Playgroud)
如果运行的PHP版本低于PHP 7.1,则抛出语法错误:
语法错误,意外的“?”,需要变量(T_VARIABLE)
该?运营商应该被删除。
PHP 7.1+
function foo(?int $value) { }
Run Code Online (Sandbox Code Playgroud)
PHP 7.0 或更低
/**
* @var int|null
*/
function foo($value) { }
Run Code Online (Sandbox Code Playgroud)
现在可以通过在类型名称前加上问号将参数和返回值的类型声明标记为可为空。这表示 NULL 和指定的类型一样,可以分别作为参数传递或作为值返回。
自PHP 7.4 起:类属性类型声明。
自PHP 8.0 起:可空联合类型
| 归档时间: |
|
| 查看次数: |
548 次 |
| 最近记录: |