No Side Effect

ID

php.no_side_effect

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Php

Tags

autoloading, reliability

Description

A PHP file should either declare symbols (classes, functions, constants) or execute side-effecting logic, but not both. This rule reports top-level side effects — echo/print, function calls such as ini_set, variable assignments, and include/require — in a file that also defines at least one symbol.

Rationale

When a file is pulled in by an autoloader to obtain a class, every top-level statement in that file runs as a side effect of the load. Output is emitted, configuration is mutated and other files are included whether or not the consumer wanted them, and the effects fire in autoloading order, which is hard to predict and almost impossible to suppress. Keeping declaration files free of executable statements makes loading them safe and idempotent. Declarations, the declare(strict_types=1) directive, namespace, use imports and conditional declaration guards are not side effects and are not flagged. A script that contains no declarations is the proper place for side effects and is left alone.

<?php
namespace App;

class Service {}                  // declaration

echo "loaded\n";                  // FLAW — output emitted just by loading the file
ini_set('display_errors', '1');   // FLAW — configuration mutated on load
require 'helpers.php';            // FLAW — pulls in another file as a side effect

// OK — a pure bootstrap script with no declarations may run side effects:
// echo "starting\n";
// require 'app.php';

Remediation

Move the executable statements into a separate bootstrap script that contains no declarations, or into a function that the consumer calls explicitly. Leave the declaration file with only its class, function and constant definitions.