Reputation: 3
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>
Upvotes: 0
Views: 275
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