Writing output in a function of a class is what I should not do?

1k views Asked by At

Lately I'm trying to adapt to the PSR standard. On the PSR-1 document it is stated that:

Files SHOULD either declare symbols (classes, functions, constants, etc.) or cause side-effects (e.g. generate output, change .ini settings, etc.) but SHOULD NOT do both.

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

2

There are 2 answers

0
deceze On BEST ANSWER

That's not what that means.

All it refers to is what happens when you include those files. The result of include 'foo.php' should either be a bunch of new symbols (classes, functions, constants) having been created, or some side effect to have happened (autoloader was added, HTML output was generated, or generally something happened). These two things should not be mixed, since you often want to load classes without also causing some inevitable side effect.

If you 1) include the file and then 2) explicitly call a function which produces a side effect, that's perfectly fine. Otherwise all code which produces side effects could not be written in classes or functions, which is simply nonsense.

2
Ja͢ck On

To sum it up with 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"; ?>