开发者

which one is better in printing out a function output in php?

In PHP, i have a function that fetch some data from database and output them.

Which one is better ?

  1. store output in a variable, for example $output and echo $output at the end of the function

    OR

  2. ec开发者_JAVA百科ho data instead of putting in $output, this causes having more than one echo statement.


None of the answers so far focus on the most important reason to do #1 : the code is more flexible! EDIT actually you should output the result of calling the function for this answer to make sense, don't echo in the function that does all the database work.

It is up to the user of the code/function to decide where and when to place the output on the page, or if at all. It can be edited, it can be compared against other data, it can be stored for use later in the script, perhaps many times over, without calling the function again.

If you echo the data right away, it's effectively 'gone' and can never be used or referred to again. It also means that when you call the function is very significant, which could be confusing if you switch to a more templated output system.

Please disregard the 'performance' answer - utter rubbish, and often the variable will be faster for a variety of reasons. As @Charles says, use code profilers as needed etc etc.


It depends. If you aren't doing anything else with the data, they they are exactly equivalent.


I think most professionals would rather do it the first way because if its passed on to other people after you then it will be easier to read and understand what it is you are trying to output.


I would actually suggest a different solution than the two you present: Return the value from the function and let the calling code decide what to do with it.

If you have a single function loading data from an external source, manipulating it and then outputting it, you have intertwined three different functions that most programmers would separate into different areas.

A much cleaner approach is to keep these different functions separate. It will make your code more reusable within your application and across applications. It will make it easier to maintain and understand. Even better, it will allow you to write unit tests for your code, since each function does one discrete thing with no side effects.

Right now, this may seem like more work with little payback, but it is going to bring you benefits in the future.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜