首页 > 文章列表 > PHP 函数的返回值有哪些类型?

PHP 函数的返回值有哪些类型?

PHP函数 返回值类型
378 2024-04-23

PHP 函数支持返回各种数据类型,包括基本类型(布尔值、整数、浮点数、字符串)、复合类型(数组、对象)、资源类型(文件句柄、数据库句柄)、空值(NULL)以及 void(PHP 8 中引入)。

PHP 函数的返回值有哪些类型?

PHP 函数的返回值类型

PHP 函数可以返回各种数据类型,包括:

  • 标量类型:布尔值、整数、浮点数、字符串
  • 复合类型:数组、对象
  • 资源类型:文件句柄、MySQL 连接句柄
  • 空(NULL)类型:没有明确值

实战案例:

返回布尔值的函数:

<?php
function is_prime(int $number): bool
{
    // 对于 1 和 2,返回真
    if ($number <= 2) {
        return true;
    }

    // 遍历 2 到 number 的平方根
    for ($i = 2; $i <= sqrt($number); $i++) {
        if ($number % $i == 0) {
            return false;
        }
    }

    return true;
}

返回数组的函数:

<?php
function get_employee_data(int $employee_id): array
{
    // 从数据库中查询员工数据
    $result = $mysqli->query("SELECT * FROM employees WHERE id = $employee_id");

    // 将结果封装到数组中
    $employee_data = $result->fetch_assoc();

    return $employee_data;
}

返回对象的函数:

<?php
class Employee
{
    public $id;
    public $name;
    public $department;
}

function create_employee(string $name, string $department): Employee
{
    $employee = new Employee();
    $employee->name = $name;
    $employee->department = $department;

    return $employee;
}

返回空值的函数:

<?php
function get_file_contents(string $filename): ?string
{
    if (file_exists($filename)) {
        return file_get_contents($filename);
    }

    return null;
}

注意:

  • PHP 7 及更高版本消除了除布尔型以外的所有返回类型。
  • 在 PHP 8 中,引入了一种新的 void 返回类型,用于表示该函数不返回任何值。