Jump to content

require vs. require_once - General Question


jd307

Recommended Posts

This is just a general question about require() and require_once(), so any opinions that you have would be very much appreciated.

 

I have always used require() when needed, however I do not generally use require_once() when the file is only NEEDED once.  I have started reading into this subject a little and there seems to be quite a discussion over good practise and security, etc. 

 

Basically my question is this: IF I only require a file ONCE, other than the fact that if you try to use the same file again and require_once() ensures that the file is not used again, is there any other reasons to really use require_once() or is it fine to keep my code using require()?

 

I am only really curious because I know that in my code, if I only require the file once... I only "import" it once, meaning I do not need PHP to check whether there has been an attempt to import it multiple times.

 

Thanks!

In most cases it's more of a precaution. It just ensures that you don't accidentally include it more than once when you know it only needs to be included once. It's always a better idea to add the safety than to say "I'll be careful". Something else to worry about is if you plan on distributing the code you want to make sure that others using your code don't make a mistake. In situation like these using require_once vs require can be helpful.

That does actually make quite a bit of sense.  I guess my applications have never been very large, therefore I know exactly what code is where and don't need includes or requires very often... but from what you are saying, I can definitly understand that (especially in larger sites and applications) it is a good precaution.

 

Thanks Alex

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.