For example, should I be doing something like:
<?php
function output_message($message,$type='success') {
?>
<p class="<?php echo $type; ?>"><?php echo $message; ?></p>
<?php
}
output_message('There were some errors processing your request','error');
?>
or
<?php
function output_message($message,$type='success') {
ob_start();
?>
<p class="<?php echo $type; ?>"><?php echo $message; ?></p>
<?php
return ob_get_clean();
}
echo output_message('There were some errors processing your request','error');
?>
I understand they both achieve the same end result, but are there benefits doing one way over the other? Or does it not even matter?
2
As longs as it’s clear from the name, comments and signature of the function that its purpose is to generate output, there’s nothing wrong with it.
What’s not good is to have output generation as a side effect of a function that also does something else (like compute and return some data, or write a file), because that’s a flagrant violation of the single responsibility principle.
If the purpose of the function is to output_message()
then I would expect the calling of the function to actually output the message.
If on the other hand, the function was called generate_message()
then I would not expect it to do the outputting:
<?php
function generate_error_message($message,$type='success') {
ob_start();
?>
<p class="<?php echo $type; ?>"><?php echo $message; ?></p>
<?php
return ob_get_clean();
}
echo generate_error_message('There were some errors processing your request','error');
?>
But I certainly agree with Michael that a function should only generate output related to its function