Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question
    
It seems like in both examples your echo is outside of the method. Even if the code was right I see no different. In both cases you are using output_message which is a method itself. –  Ramhound Sep 13 '12 at 16:28
    
@Ramhound - the functions are different. One returns the data as a variable, the other outputs it. I think you may have misunderstood what I was asking here. –  Nick Sep 14 '12 at 13:09

2 Answers 2

up vote 17 down vote accepted

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.

share|improve this answer

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.