Including Files : Advanced

Before I touched on one of the most useful basic benefit of using PHP and that was removing code that is repeated in a web site, placing it in its own file and just including it into your page using the include() function.

There are 3 further functions that do similar operations however also have their own use.

require() – this is virtually the same as include(). You use it in the same manner however the difference and possible benefit is that when a file is called using include, which doesn’t exist, a warning is stated on the page (unless it is supressed) but the page continues to execute the remaining code. However when you call a non existent file using the require() function then this causes a fatal error on the page and terminates the script.

include_once() – this does as it says, it includes the file once. If you have already included the file before then when you use this function on a file it will not include it a second time.

require_once() – a combination of the two descriptions above. If the file does not exist it will call a fatal error and terminate the script however if the file has already been required before then it will not be executed a second time.

These functions have a lot of more advanced uses which I’ll look at as time goes on but for now a simple rule of thumb is, if the content of an include file should only be run once, use require_once() or include_once(). Which one you use is personal preference although it’s recommended to use require() where ever possible, I personally use include() unless I really want to kill a script!

A good example of using these is when you have your database connection details in an include file, so that you only have one real instance of them to update if/when you move servers. Unless you close your connection midway through your code (not recommended) then you cannot open a connection to the database for a second time. By using the include_once() function you can be sure that after the first call to the connection file, no subsequent calls will be executed.

I’ll be getting onto databases soon 😉

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *