返回值

与参数类型声明类似 ,返回类型声明指定将从函数返回的值的类型。 返回类型声明可以使用相同的类型。

类型 描述
类/接口名称 返回值必须是给定的类或实现接口的实例
self 返回值必须是与定义方法的类相同的实例
array 返回值必须是数组
callable 返回值必须是可调用类型
bool 返回值必须是布尔类型
float 返回值必须是浮点型
int 返回值必须是整型
string 返回值必须是字符串

值通过使用可选的返回语句返回。可以返回包括数组和对象的任意类型。返回语句会立即中止函数的运行,并且将控制权交回调用该函数的代码行。如果省略了 return ,则返回值为 NULL

<?php

/**
 * Calculate the cube of an integer.
 *
 * @param  int    $number
 * @return int
 */
function foo(int $number): int
{
    return $number ** 3;
}

foo(2);

返回一个数组以得到多个返回值。

<?php

/**
 * Return an array.
 *
 * @param  void
 * @return array
 */
function foo(): array
{
    return [2, 4, 5];
}

list($foo, $bar, $baz) = foo();

从函数返回一个引用。

<?php

class Foo
{
    /**
     * Just a test property.
     *
     * @var int
     */
    public int $property = 5;

    /**
     * Return a reference.
     *
     * @param  void
     * @return int
     */
    public function &method(): int
    {
        return $this->property;
    }
}

$foo = new Foo();
$property = &$foo->method();
var_dump($property); // int(5)

$foo->property = 6;
var_dump($property); // int(6)

基本类返回类型声明。

<?php

/**
 * Basic class return type declaration.
 *
 * @param  string $class
 * @return Foo
 */
function foo(string $class): Foo
{
    return new $class;
}

class Foo
{
    //
}

class Bar extends Foo
{
    //
}

class Baz
{
    //
}

var_dump(foo('Foo')); // object(Foo)#1 (0) { }
var_dump(foo('Bar')); // object(Bar)#1 (0) { }
var_dump(foo('Baz')); // PHP Fatal error:  Uncaught TypeError: Return value of foo() must be an instance of Foo, instance of Baz returned.

基本接口返回类型声明。

<?php

/**
 * Basic interface return type declaration.
 *
 * @param  string $class
 * @return Foo
 */
function foo(string $class): Foo
{
    return new $class;
}

interface Foo
{
    //
}

class Bar implements Foo
{
    //
}

class Baz
{
    //
}

var_dump(foo('Bar')); // object(Bar)#1 (0) { }
var_dump(foo('Baz')); // PHP Fatal error:  Uncaught TypeError: Return value of foo() must implement interface Foo, instance of Baz returned.

严格类型也会对返回类型声明产生影响。在严格模式下,返回的值必须是指定的类型,否则将引发 TypeError

<?php

declare(strict_types=1);

/**
 * Calculate the quotient of two integers.
 *
 * @param  int    $a
 * @param  int    $b
 * @return int
 */
function foo(int $a, int $b): int
{
    return $a / $b;
}

var_dump(foo(2, 1)); // int(2)
var_dump(foo(2, 4)); // PHP Fatal error:  Uncaught TypeError: Return value of foo() must be of the type int, float returned.

在默认的弱类型下,如果返回的值不是指定的类型,则它将被强制转换为正确的类型。

<?php

/**
 * Calculate the quotient of two integers.
 *
 * @param  int    $a
 * @param  int    $b
 * @return int
 */
function foo(int $a, int $b): int
{
    return $a / $b;
}

var_dump(foo(2, 1)); // int(2)
var_dump(foo(2, 4)); // int(0)

results matching ""

    No results matching ""