Avoiding side effects in a file that defines symbols is an important principle in PHP development. A file should declare symbols (like classes, functions, or constants) and cause no other side effects. Side effects include but are not limited to: generating output, explicit use of require or include, connecting to external services, modifying ini settings, emitting errors or exceptions, modifying global or static variables, reading from or writing to a file, and so on.
This rule is essential because it promotes the separation of concerns, which is a fundamental aspect of good software design. It helps to maintain the readability, maintainability, and testability of your code. Side effects can lead to hidden dependencies, making the code harder to understand and manage.
To adhere to this rule, always ensure that your PHP files either define symbols (like classes, functions, or constants) or cause side effects (like generating output or changing ini settings), but not both. For instance, if a file defines a class, it shouldn’t also connect to the database. Instead, the database connection should be done in a different file or within a method or function when needed. This way, you can maintain a clear separation between the definition of your symbols and the implementation of your application logic.
Non-Compliant Code Examples
<?phpclassTest{}print'testing!';
Compliant Code Examples
<?phpclassTest{}classMain{}
Seamless integrations. Try Datadog Code Analysis
Datadog Code Analysis
Try this rule and analyze your code with Datadog Code Analysis
How to use this rule
1
2
rulesets:- php-security # Rules to enforce PHP security.
Create a static-analysis.datadog.yml with the content above at the root of your repository
Use our free IDE Plugins or add Code Analysis scans to your CI pipelines