首頁  >  文章  >  後端開發  >  PHP 函數的傳回值有哪些型別?

PHP 函數的傳回值有哪些型別?

PHPz
PHPz原創
2024-04-11 13:21:02546瀏覽

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 回傳類型,用於表示函數不傳回任何值。

以上是PHP 函數的傳回值有哪些型別?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn