Writing output in class functions is what I shouldn't do?

Recently, I am trying to adapt to the PSR standard. The PSR-1 document states that:

Files MUST either declare characters (classes, functions, constants, etc.) or cause side effects (for example, generate output, change .ini settings, etc.), but MUST NOT do both.

Does this mean that writing output (say echo '<b>some bold text</b>'; ) in a function that resides in a class is something that I should not do?

+6
source share
2 answers

This is not what it means.

All this relates to what happens when you include those files. The result of include 'foo.php' should be either a set of new characters (classes, functions, constants) that were created, or some kind of side effect (an autoloader was added, HTML output was output, or something happened at all). These two things should not be confused, since you often want to load classes without causing an inevitable side effect.

If you 1) include file, and then 2) explicitly call a function that creates a side effect, this is completely normal. Otherwise, all the code that creates side effects cannot be written in classes or functions, which is simply nonsense.

+5
source

To summarize the examples.

Bad example (mixed)

 <?php namespace Foo; class Bar { // ... } ?> <b>some text here</b> 

Good example # 1 (class declaration)

 <?php namespace Foo; class Bar { // ... } 

Good example # 2 (template)

 <b>some text here</b> <?php echo "hello world"; ?> 
0
source

Source: https://habr.com/ru/post/988901/


All Articles