简体   繁体   中英

echo or return from a function

I have a function which echos out common code for a web page. If I do the code like this:

echo '<tr>'; 
CSCell("{$row['home_team']}/{$row['home_team']}",'home_home',$row, 1);
echo '</tr><tr>'; 
CSCell("{$row['home_team']}/Draw",'home_draw',$row, 1);
echo '</tr><tr>'; 

It works without issue. If I do it like this:

echo '<tr>' . CSCell("{$row['home_team']}/{$row['home_team']}",'home_home',$row, 1) . '</tr>';
echo '<tr>' . CSCell("{$row['home_team']}/Draw",'home_draw',$row, 1) . '</tr>';

It outputs an additional empty row for each line of code. Presumably it initially echos <tr> then the function outputs data then it returns null (because no return specified) then it begins the echo again (without re-calling the function & prints <tr> empty string </tr>).

How to stop it re-echoing the tr HTML? The function only contains td echo data?

I'm too lazy to make it return now because of the other parts it is referenced in where it needs to echo. How to modify the function so it can be used to echo and return?

Since you are already relying on the output in other code, just add a fifth parameter to the function to tell it to echo or return :

function CSCell($a, $b, $c, $d, $return=false) {
    // build $output
    if($return) { return $output; }
    echo $output;
}

Then call it with $return = true :

echo '<tr>' . CSCell("{$row['home_team']}/Draw", 'home_draw', $row, 1, true) . '</tr>';

If you can't modify the function, then build a wrapper and buffer the output and return. I don't know what the function looks like so you need to check the arguments or rely on the CSCell() function to validate them:

function _cscell($a, $b, $c, $d) {
    ob_start();
    CSCell($a, $b, $c, $d);
    return ob_end_clean();
}

Then call the wrapper function:

echo '<tr>' . _cscell("{$row['home_team']}/Draw", 'home_draw', $row, 1) . '</tr>';

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