Re: Printing within functions

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Philip Thompson napsal(a):
Hi. I thought of this when I read the emails about using functions or
includes...

What are your thoughts about *printing* things from within functions? For
example:

<?php
function printSomething () {
    echo "Something about nothing. ";
    echo "Another something.";
}

function something () {
    $text = "Something about nothing. ";
    $text .= "Another something.";
    return $text;
}
?>
<html>
...
<p><?php printSomething (); ?></p>
<p><?php echo something (); ?></p>
...
</html>

Obviously, these are over-simplified functions, but you get the point.
Nonetheless, do you tend to print things within functions or pass the
results back and then print them? I understand it may depend on the current
context, but which way do you lean and is one way or the other considered
*better practice*?

Thanks,
~Philip




It is generally better to use result returning functions instead of direct printing. You can do more things with data in some $result variable than with data waiting to be outputted in some buffer. At least you can change your mind and call function from other function. You do not need to distinguish between functions "printing results" and "calculating something". Let's say you have function to create HTML page. It sounds like this function could print directly to the input. But imagine you need to include this whole page in some other page in some HTML element. The second (and more important) difference is that you can output data in other order than they have been generated and you can even discard some of them.
Lets say you are generating tree-like something into HTML table.:
+-----------------+
|       ABC       |
| +-------+ +---+ |
| |  AB   | |   | |
| |+-+ +-+| |   | |
| ||A| |B|| | C | |
| |+-+ +-+| |   | |
| +-------+ +---+ |
+-----------------+


You have function to generate leaf cell (A,B,C) and function to combine two cells into one (A+B=AB). In this case you need to generate cells A,B and their contents combined into cell AB. And the same with AB+C. This would be very difficult with direct printing. And my personal experience is that when I start with something really simple, just to test something and I am lazy and use echo(), then almost every time code gets bigger and I end up with replacing echo() for $result .= :-)

Radek

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux