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

188 views Asked by At

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?

1

There are 1 answers

0
Mat On BEST ANSWER

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.