简体   繁体   中英

php - How to pass parameters to a function

I'm pretty sure this is a very basic question to all of you, but i'm new with php, and i don't really get it... basically i've created a function in which i need to pass two parameters.

My functions is this:

function displayRoomDetails($customerRooms, $test)
{
    foreach ($customerRooms as $room) {
        $test.= $room->name;
    };
}

it is a very basic function, but will do for this example.

Now, i'm creating templates to display several information, and i have 3 different layout where i need to display the same info but styled differently, so my approach was:

template1 .= '<span>';

if (!$customerRooms == "") {
    displayRoomDetails($customerRooms,"template1");
};

template1 .= '</span>';

It should be pretty easy to understand, basically i'm calling the same functions in all the different templates passing as a parameter the template name and trying to append the results to the right template.

The problem i've got is this: According to this example here -> http://www.w3schools.com/php/showphp.asp?filename=demo_function3

i should be able to do this exactly like i did, but when i try, when i debug my function, $template doesn't take the passed value as i though it would, but it is still called $test and not $template1...

What am i doing wrong?

Thanks

Try these changes:

function displayRoomDetails($customerRooms, &$test)

And

$template1 .= '<span>';
if ($customerRooms != "") {
  displayRoomDetails($customerRooms, $template1);
};
$template1 .= '</span>';

From what I understand you want to append some text to the template1 variable using the displayRoomDetailsFunction

Some things to fix:

  1. template1 should be $template1
  2. You should be passing the $template1 not the "template1" (ie the variable itself not its name).
  3. If you want to modify this variable you need to either:
    • pass it as reference , which you can do by changing the function's declaration to: function displayRoomDetails($customerRooms, &$test)
    • return new string from function and assign it to the $template1 by adding return $test; just after your foreach block and changing the call to $template1 .= displayRoomDetails($customerRooms,$template1);

Additional note: if $customerRooms is an array, it'd be better to check if it's not empty using count() than !$customerRooms == "" , see @andrew's comment for details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM