Why `require_once` is better than `require`

I am not sure to understand why require_once is preferred to require. It is said :

Because including the same file multiple times could have unpredictable results, the “once” versions are preferred.

But if we know how and when the code is used, we should know that one file will be included one or more times isn’t it?

Require_once adds a condition to know if the file has been loaded but if we already know that …why ask PHP for the solution we already have?

Hello @lperamo

thank you for your inquiry.
I think you agree that loading the same file can lead to unexpected behavior. For example, variables can be overwritten, or multiple declarations of classes, methods, or constants can be attempted, leading to errors.

We want to support users with this rule to avoid this risk. require_once protects against these overwrites or errors caused by multiple declarations. This PHP internal logic can of course also be achieved by custom code and condition. Also, it is conceivable that the reloading of the same file is intended.

In this case, this issue can be marked as ‘Won’t fix’ and noted with the reason for other contributors. If this rule is noisy to you in the context of your project, you can of course deactivate it.

I hope I have understood your request correctly and could give you a satisfactory answer.

Best,
Nils

Hello @Nils_Werner ,

Indeed, I agree that loading the same file can lead to unexpected behavior…if we do no master completely the code. I guess, you put caution above performance. IMO, I find that it is the easy solution but I want to maximize performance so I’ll probably mark it as won’t fix as you said (with the reason of course :slight_smile: ).

Sometimes I use require_once, but it only concerns some particular cases and I put a comment about those. I will mark your answer as the solution.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.