> For the complete documentation index, see [llms.txt](https://php7.shujuwajue.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://php7.shujuwajue.com/php-71x-xin-te-xing/xin-te-xing/ke-wei-kong-ff08-nullable-ff09-lei-xing.md).

# 可为空（Nullable）类型

**官方解释：**&#x7C7B;型现在允许为空，当启用这个特性时，传入的参数或者函数返回的结果要么是给定的类型，要么是[null](https://php.net/manual/zh/language.types.null.php)。可以通过在类型前面加上一个问号来使之成为可为空的。

**大话解释：**&#x5B98;方的中文翻译是有歧义的，经过测试正确的解释应该是：类型在7.0的时候,不能传入null值，也不能什么都不传，两种情况都会报错，7.1中加上一个问号问号来使之可以传入为null的类型，但是什么值都不传的情况仍然会报错

> 同时适用于函数和对象的方法中

## 形参类型声明：

### 函数中，如下代码：

```php
function test(string $name)
{
    var_dump($name);
}

test('tpunt');
test(null); //此行会引发的错误
test();　//此行会引发的错误
```

### 对象的方法中，如下代码：

```php
class Tests
{
    function test(string $name)
    {
        var_dump($name);
    }

}

$test = new Tests();
$test->test('tpunt');
$test->test(null); //由此会行引发的错误
$test->test();　//由此会行引发的错误
```

PHP7.0 中会报错．如下：

```
Fatal error: Uncaught TypeError: Argument 1 passed to test() must be of the type string, null given, called in .....
TypeError: Argument 1 passed to test() must be of the type string, null given, called in ....
```

**在PHP7.1当中只需要在类型前面加** `?` **即可解决null 报错，什么值都不传的情况仍然会报错．**

```
?string $name
```

结果

```
test();　//此行仍然会引发的错误
－－－－－－－－－－－－－－－－－－－－－－－－－－
Fatal error: Uncaught TypeError: Argument 1 passed to test() must be of the type string, null given, called in .....
TypeError: Argument 1 passed to test() must be of the type string, null given, called in ....
```

进一步结果可以解决`test()`这种情况的报错，但是如果以上函数的参数定义为 ?Bar $bar = null 的形式，则第三种写法也是可行的。因为 = null实际上相当于 ? 的超集，对于可空类型的参数，可以设定 null 为默认值。

```php
function test(?string $name = null)
{
    var_dump($name);
}

test('tpunt');
test(null); // ok
test(); // ok
```

以上代码即可解决．同样适用于对象的方法中的形参类型声明．

## 返回类型声明：

```php
function answer1(): ?int  {
    return null; //ok
}
var_dump(answer1());

function answer2(): ?int  {
    return 42; // ok
}
var_dump(answer2());

function answer3(): ?int  {
    return ''; //由此会行引发的错误 
}
var_dump(answer3());
```

对象候总类方法的返回类型声明就不再举例了．
