Why is this an issue?

Namespaces should be preferred over the include or require functions in PHP because they provide a cleaner and more organized approach for managing code dependencies. Namespaces allow you to logically group related classes, functions, and constants, preventing naming conflicts and improving code readability. They also promote code reusability by enabling modularization and encapsulation. On the other hand, using include or require functions directly can lead to a cluttered global namespace and make it harder to track and manage dependencies, especially in larger projects.

Exceptions

This rule doesn’t raise issues on autoload.php files. This file is typically generated by Composer that provides an autoloading mechanism for classes and functions. Composer is a dependency management tool for PHP that simplifies the process of integrating external libraries and packages into your project.

How to fix it

It is recommended to use the PSR-4 autoloading standard and to use Composer to manage the loading of classes and functions.

Code examples

Noncompliant code example

require_once './shop/modules/vegetable/src/entity/Tomato.php';

Compliant solution

use Shop\Vegetable\Tomato

How does this work?

To import classes and functions with namespaces using Composer in PHP you have to ensure that the project is set up to use Composer and have a valid composer.json file in the root directory. Make sure the namespace corresponds to the directory structure of your classes.

Resources

Documentation