# Void 函数

在PHP 7 中引入的其他返回值类型的基础上，一个新的返回值类型void被引入。 返回值声明为 void 类型的方法要么干脆省去 return 语句，要么使用一个空的 return 语句。 对于 void 函数来说，null 不是一个合法的返回值。

```php
<?php
function swap(&$left, &$right) : void
{
    if ($left === $right) {
        return;
    }

    $tmp = $left;
    $left = $right;
    $right = $tmp;
}

$a = 1;
$b = 2;
var_dump(swap($a, $b), $a, $b);
```

以上代码

* 当`$a = 1;　$b = 2;` 并不会进入到if语句中，所以会继续执行，最后也没有返回到任何的值．

```
null
int(2)
int(1)
```

* 当`$a = 1;　$b = １;`则会进入到if语句中，return返回．

```
null
int(1)
int(1)
```

由于返回类型为void，则两种情况１．无写返回值 ２．直接return 方式返回，获取返回结果均会得到一个null值．

试图去获取一个 void 方法的返回值会得到 null ，并且不会产生任何警告。这么做的原因是不想影响更高层次的方法。

> 注意，不但适用于函数中，也同样适用于对象的方法中

如下示例：

```php
<?php
error_reporting(E_ALL);
ini_set('display_errors', true);


class Tests
{
    function swap(&$left, &$right) : void
    {
        if ($left === $right) {
            return;
        }

        $tmp = $left;
        $left = $right;
        $right = $tmp;
    }
}

$test = new Tests();
$a = 1;
$b = 2;
var_dump($test->swap($a, $b), $a, $b);
```

结果：

```
null
int(2)
int(1)
```

## 补充整理总结：

PHP7.0 添加了指定函数返回类型的特性，但是返回类型却不能指定为 `void`，7.1 的这个特性算是一个补充，但是让人大跌眼镜的是一下会报错：

```php
<?php
function should_return_nothing(): void {
    return 1; // Fatal error: A void function must not return a value
}
```

以下两种情况都可以通过验证：

```php
<?php
function lacks_return(): void {
    // valid
}

function returns_nothing(): void {
    return; // valid
}
```

定义返回类型为 `void` 的函数不能有返回值，即使返回 `null` 也不行：

```php
<?php
function returns_one(): void {
    return 1; // Fatal error: A void function must not return a value
}

function returns_null(): void {
    return null; // Fatal error: A void function must not return a value
}
```

此外 `void` 也只适用于返回类型，并不能用于参数类型声明，或者会触发错误：

```php
<?php
function foobar(void $foo) { // Fatal error: void cannot be used as a parameter type
}
```

类函数中对于返回类型的声明也不能被子类覆盖，否则会触发错误：

```php
<?php
class Foo
{
    public function bar(): void {
    }
}

class Foobar extends Foo
{
    public function bar(): array { // Fatal error: Declaration of Foobar::bar() must be compatible with Foo::bar(): void
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://php7.shujuwajue.com/php-71x-xin-te-xing/xin-te-xing/void-han-shu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
