PHP – Is It Bad Practice to Output Within a Function?

functionsPHPprogramming practices

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?

Best Answer

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.

Related Topic