Home >Backend Development >PHP Tutorial >What types of return values ​​do PHP functions have?

What types of return values ​​do PHP functions have?

PHPz
PHPzOriginal
2024-04-11 13:21:02640browse

PHP functions support returning various data types, including basic types (Boolean values, integers, floating point numbers, strings), composite types (arrays, objects), resource types (file handles, database handles), null values ​​(NULL ) and void (introduced in PHP 8).

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

Return value type of PHP function

PHP function can return various data types, including:

  • Scalar type: Boolean, integer, floating point number, string
  • Composite type: Array, object
  • Resources Type: File handle, MySQL connection handle
  • Empty (NULL) type: No clear value

Actual case:

Function that returns a Boolean value:

<?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;
}

Function that returns an array:

<?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;
}

Function that returns an object :

<?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;
}

Function that returns null value:

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

    return null;
}

Note:

    ##PHP 7 and Later versions eliminated all return types except Boolean.
  • In PHP 8, a new void return type was introduced to indicate that the function does not return any value.

The above is the detailed content of What types of return values ​​do PHP functions have?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn