2

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

Sammitch
  • 30,782
  • 7
  • 50
  • 77
  • Well, does it _have_ a side effect? Declarations create new function/class names, an instantiation which assigns to a variable creates a new variable. That's generally not much different, and if it's expected what names will be created and it has no other actual side effects… then it doesn't. – deceze Jun 07 '23 at 14:18
  • well, I think that object creation can also be perceived as activating class just like a function which can be called with this - "()" – zaza mirotadze Jun 07 '23 at 15:43
  • Sure, but if it doesn't _have any side effect_, then that's neither here nor there. Even for just "defining" something, you may be running some functions; maybe to determine what extensions are available and conditionally defining different functions or such. – deceze Jun 07 '23 at 17:23

1 Answers1

1

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';
  }
}
Sammitch
  • 30,782
  • 7
  • 50
  • 77