Re: Printing within functions
| From: | Radek Hladik | Date: | Tue, 13 Nov 2007 02:20:55 +0000 |
| Subject: | Re: Printing within functions | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-264414@lists.php.net to get a copy of this message | ||
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 () {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.: +-----------------+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
| 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