如何返回 PHP 自定义函数的值?

如何返回 PHP 自定义函数的值?
最新回答
承诺算ィ麽

2022-07-09 07:19:00

在 PHP 中,自定义函数通过 return 语句返回值,支持多种数据类型(字符串、数字、数组、对象等)。以下是详细说明和示例:

1. 基本语法function 函数名(参数列表): 返回类型 { // 函数逻辑 return 值; // 返回值类型需与声明一致}
  • 返回类型(可选):如 : string、: array,未指定时默认返回任意类型,无返回值时默认为 null。
  • void:若函数无返回值,可声明为 : void。
2. 返回值类型示例(1) 返回字符串function greet(string $name): string { return "Hello, $name!";}echo greet("Alice"); // 输出: Hello, Alice!(2) 返回数组function getUserData(int $id): array { return ["name" => "John", "age" => 30];}$data = getUserData(1);echo $data["name"]; // 输出: John(3) 返回数字function add(int $a, int $b): int { return $a + $b;}echo add(3, 5); // 输出: 8(4) 返回对象class User { public $name;}function createUser(): User { $user = new User(); $user->name = "Bob"; return $user;}$user = createUser();echo $user->name; // 输出: Bob3. 无返回值函数function logMessage(string $message): void { echo "[LOG] $message"; // 无 return 语句}logMessage("Process started"); // 输出: [LOG] Process started4. 注意事项
  1. 类型匹配:若声明返回类型(如 : int),但返回其他类型(如字符串),PHP 会尝试自动转换,失败则抛出 TypeError(严格模式下)。
  2. 默认返回值:未执行 return 的函数返回 null。
  3. 提前返回:可在条件分支中使用 return 提前退出函数:function checkAge(int $age): string { if ($age < 18) return "Minor"; return "Adult";}
5. 实战案例整合// 返回混合类型(PHP 8+ 支持联合类型)function findUser(int $id): array|null { $users = [1 => ["name" => "Alice"], 2 => ["name" => "Bob"]]; return $users[$id] ?? null;}$user = findUser(1);if ($user) echo $user["name"]; // 输出: Alice

通过 return 语句,PHP 自定义函数可以灵活返回所需数据,结合类型声明可提升代码可读性和安全性。