phppsr-1

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


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?


Solution

  • 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.