函数通过 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 函数如何返回特定值
在 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