Difference – include and include_once with example

We all know both the functions include and include_once in PHP will insert the content of the PHP file into another PHP file. Sometimes people may ask the difference especially in Interviews, you may have confused how to explain the difference between them.

Just reading a description without doing a practical experiment will not help in this case. So it is always better to do an experiment to understand it fully.

Lets begin the test:

There are two files we are going to use:

1. functions.php

2. index.php

In index.php I have included the functions.php twice, what would be the result you think??

The result is a Fatal Error, something like this,

How do you fix this now?
Fix this by using include_once() instead of include().

index.php (modified)

Now you can see the output without any fatal error.

So, basically include_once checks if the file is already loaded, if loaded then it won’t load.

Related Posts

Leave a Reply