phppsr-1

Is class declaration and object initialization in the same file PSR-1 compliant?


PSR-1 states:

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.

Let's suppose we have following code:

// db.php file
class Db{
    // Some code here
}

$DB = new Db();

Does instantiating an object count as causing a side effect? In other words, is the above code PSR-1 compliant?


Solution

  • According to the PSR-1

    "Side effects" include but are not limited to: [...] connecting to external services [...]

    And more generally, it is specified :

    The phrase "side effects" means execution of logic not directly related to declaring classes, functions, constants

    So the answer is : it is not PSR-1 compliant.

    You should include your db.php file in your main logic file. And then instanciate your DB object.