singing_mower
singing_mower

Reputation: 3

Calling a php function as a parameter inside a function call

I'm trying to printing data from a database to the hcard format:

...
<span class='n'>
<span class="given-name">John</span>
...
</span>

Then I created this php function:

function print_row ($html_tag, $type, $value) {
    echo '<'.$html_tag.' class="'.$type.'">'.$value.'</'.$html_tag.'>';
}

// Calling function
print_row('span', 'given_name', 'John');

// Output
<span class="given_name">Nathan</span>  

This worked as I expected until I tried calling my print_row function as a parameter of the print_row function.

print_row('span', 'n', print_row('span', 'given_name', 'Nathan'));

// Output
<span class="given_name">Nathan</span>
<span class="n"></span>

// Wanted Output
<span class="n"><span class="given_name">Nathan</span></span>
  1. Why is my second 'print_row' function call not inside my first'print_row' function call?
  2. Is this even impossible? (PHP - Can I pass a function name as a function argument?)

Upvotes: 0

Views: 275

Answers (2)

Robin Castlin
Robin Castlin

Reputation: 10996

Almost always use return instead of echo in function calls.

Why? Because return returns the data and lets you both store AND echo it. echo just renders it to the browser.

An example of a basic return and echo function is print_r(). It either does a echo, or a return if second parameter is TRUE.


You should change

function print_row ($html_tag, $type, $value) {
    echo '<'.$html_tag.' class="'.$type.'">'.$value.'</'.$html_tag.'>';
}

to

function print_row ($html_tag, $type, $value) {
    return '<'.$html_tag.' class="'.$type.'">'.$value.'</'.$html_tag.'>';
}

and echo the function accordingly on existing places.
That or add a 4th parameter that return instead of echo:

function print_row ($html_tag, $type, $value, $bool = FALSE) {
    $str = '<'.$html_tag.' class="'.$type.'">'.$value.'</'.$html_tag.'>';
    if ($bool)
        return $str;
    else echo $str;
}

print_row('span', 'n', print_row('span', 'given_name', 'Nathan', TRUE));
// Added a ', TRUE' at the second last ')'

Upvotes: 4

Tim
Tim

Reputation: 6441

You have to return the value from the function, not echo it.

Upvotes: 2

Related Questions