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

PHP 函数的返回值类型
PHP 函数可以返回各种数据类型,包括:
实战案例:
立即学习“PHP免费学习笔记(深入)”;
返回布尔值的函数:
<?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 函数的返回值有哪些类型?的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号