函数通过 return 语句返回特定值,若要返回多个值,可用数组或对象。1. 返回字符串:return "hello, world!"; 2. 返回数字:return $amount + ($amount * $tax_rate); 3. 返回数组:return ['name' => 'john doe', 'email' => 'john.doe@example.com', 'age' => 30]; 4. 返回引用:return &$balance;

在 PHP 中,函数可以返回特定值以供调用它们的代码使用。可以通过使用 return 语句来实现,该语句会立即退出函数并返回一个值。
return 语句的一般语法如下:
return value;
其中 value 是要返回的值。
立即学习“PHP免费学习笔记(深入)”;
示例 1:返回一个字符串
function get_greeting() {
return "Hello, world!";
}
$greeting = get_greeting();
echo $greeting; // 输出 "Hello, world!"示例 2:返回一个数字
function calculate_total($amount, $tax_rate) {
return $amount + ($amount * $tax_rate);
}
$total = calculate_total(100, 0.1);
echo $total; // 输出 110示例 3:返回一个数组
function get_user_data($id) {
// 查询数据库并检索数据
$data = [
'name' => 'John Doe',
'email' => 'john.doe@example.com',
'age' => 30
];
return $data;
}
$user_data = get_user_data(1);
echo $user_data['name']; // 输出 "John Doe"PHP 支持通过数组或对象返回多个值。
function get_student_info($id) {
// 查询数据库并检索数据
$info = [
'name' => 'Jane Doe',
'major' => 'Computer Science',
'gpa' => 3.8
];
return $info;
}
$student_info = get_student_info(2);
echo $student_info['name']; // 输出 "Jane Doe"
echo $student_info['major']; // 输出 "Computer Science"在某些情况下,您可能需要返回对变量或对象的引用。为此,请使用 & 操作符。
function &get_account_balance() {
static $balance = 1000;
return $balance;
}
$balance =& get_account_balance();
$balance += 100;
echo $balance; // 输出 1100以上就是PHP 函数如何返回特定的值的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号