is creating an instance of a class considered as side effect or declaration in PHP Standards Recommendations?

82 Views Asked by At

is creating an instance of class considered as side effect or declaration? how it is considered in PHP recommendation standards.

1

There are 1 best solutions below

0
Sammitch On

Specifically with regard to PSR-1 [Basic Coding Style], Section 2.3:

  • Neither declaring nor instantiating a class is inherently a side effect.
  • Code contained in a file should only do one or the other.

Eg, this would be a "side effect rule violation" if it was in a single file:

class Foo {
  // ...
}

$f = new Foo();

The instantiation at the end would inherently affect the state of the execution into which it was included by declaring a new variable in the local scope.

Though, for clarity, instantiating new objects during the execution of methods is fine, as these variables are contained to the object's scope. Eg:

class Foo {
  protected $thing;
  public function __construct() {
    $this->thing = new Thing();
  }
}

The above code is fine as far as PSR-1 side-effects go, but runs afoul of more esoteric coding style conventions like Composition/Dependency Injection/SOLID/etc if you're into those things.

All that said, be aware that the term "side-effects" has different meanings depending on the context. For example: a function that modifies data outside of its local scope such as global state could be said to have side-effects, but could be written in a manner that it is not considered a side-effect in the context of PSR-1. Eg:

class Foo {
  public function __construct() {
    global $foo;
    $foo = 'bar';
  }
}