php - 如何将参数传递给函数
php - How to pass parameters to a function
我很确定这对你们所有人来说都是一个非常基本的问题,但我是 php 的新手,我不太明白...
基本上我已经创建了一个函数,我需要在其中传递两个参数。
我的功能是这样的:
function displayRoomDetails($customerRooms, $test)
{
foreach ($customerRooms as $room) {
$test.= $room->name;
};
}
这是一个非常基本的功能,但可以用于此示例。
现在,我正在创建模板来显示多个信息,我有 3 种不同的布局,我需要在其中显示相同的信息但样式不同,所以我的方法是:
template1 .= '<span>';
if (!$customerRooms == "") {
displayRoomDetails($customerRooms,"template1");
};
template1 .= '</span>';
应该很容易理解,基本上我在所有不同的模板中调用相同的函数,将模板名称作为参数传递,并尝试将结果附加到正确的模板。
我遇到的问题是:
根据这里的这个例子->
http://www.w3schools.com/php/showphp.asp?filename=demo_function3
我应该能够完全像我那样做,但是当我尝试时,当我调试我的函数时,$template 并没有像我那样接受传递的值,但它仍然被称为 $test
而不是 $template1...
我做错了什么?
谢谢
试试这些改变:
function displayRoomDetails($customerRooms, &$test)
和
$template1 .= '<span>';
if ($customerRooms != "") {
displayRoomDetails($customerRooms, $template1);
};
$template1 .= '</span>';
据我了解,您想使用 displayRoomDetailsFunction
将一些文本附加到 template1
变量
一些需要解决的问题:
template1
应该是 $template1
- 您应该传递
$template1
而不是 "template1"
(即变量本身而不是它的名称)。
- 如果你想修改这个变量,你需要:
- 将其作为 reference 传递,您可以通过将函数的声明更改为:
function displayRoomDetails($customerRooms, &$test)
- return 函数中的新字符串并将其分配给
$template1
,方法是在 foreach
块之后添加 return $test;
并将调用更改为 $template1 .= displayRoomDetails($customerRooms,$template1);
补充说明:如果 $customerRooms
是一个数组,使用 count()
检查它是否不为空比 !$customerRooms == ""
更好,参见@andrew 的评论了解详情
我很确定这对你们所有人来说都是一个非常基本的问题,但我是 php 的新手,我不太明白... 基本上我已经创建了一个函数,我需要在其中传递两个参数。
我的功能是这样的:
function displayRoomDetails($customerRooms, $test)
{
foreach ($customerRooms as $room) {
$test.= $room->name;
};
}
这是一个非常基本的功能,但可以用于此示例。
现在,我正在创建模板来显示多个信息,我有 3 种不同的布局,我需要在其中显示相同的信息但样式不同,所以我的方法是:
template1 .= '<span>';
if (!$customerRooms == "") {
displayRoomDetails($customerRooms,"template1");
};
template1 .= '</span>';
应该很容易理解,基本上我在所有不同的模板中调用相同的函数,将模板名称作为参数传递,并尝试将结果附加到正确的模板。
我遇到的问题是: 根据这里的这个例子-> http://www.w3schools.com/php/showphp.asp?filename=demo_function3
我应该能够完全像我那样做,但是当我尝试时,当我调试我的函数时,$template 并没有像我那样接受传递的值,但它仍然被称为 $test
而不是 $template1...
我做错了什么?
谢谢
试试这些改变:
function displayRoomDetails($customerRooms, &$test)
和
$template1 .= '<span>';
if ($customerRooms != "") {
displayRoomDetails($customerRooms, $template1);
};
$template1 .= '</span>';
据我了解,您想使用 displayRoomDetailsFunction
template1
变量
一些需要解决的问题:
template1
应该是$template1
- 您应该传递
$template1
而不是"template1"
(即变量本身而不是它的名称)。 - 如果你想修改这个变量,你需要:
- 将其作为 reference 传递,您可以通过将函数的声明更改为:
function displayRoomDetails($customerRooms, &$test)
- return 函数中的新字符串并将其分配给
$template1
,方法是在foreach
块之后添加return $test;
并将调用更改为$template1 .= displayRoomDetails($customerRooms,$template1);
- 将其作为 reference 传递,您可以通过将函数的声明更改为:
补充说明:如果 $customerRooms
是一个数组,使用 count()
检查它是否不为空比 !$customerRooms == ""
更好,参见@andrew 的评论了解详情