PHP include_once() is a powerful function that allows developers to include and execute a file in their code just once, even if it is called multiple times. This can be incredibly useful for avoiding errors caused by duplicate code or conflicting functions, as well as improving the performance and organization of the code.
This article aims to provide a comprehensive understanding of PHP’s include_once() function, covering its syntax, parameters, and practical usage examples.
What is the PHP include_once() Function?
The PHP include_once() function is a convenient way to include a PHP file only once in your code. It determines whether the file is already included before including it again. Unlike the regular include() function, include_once() won’t load the file if it has already been included, and it returns true.
Syntax: The PHP include_once() function has the following syntax:
Parameter: This function takes only one argument:
- name/path_of_file: Specify the file having the .php extension which you want to include in another PHP file.
Return value: The function will return true if the file is successfully included otherwise, it will return a warning.
How Does PHP include_once Function Work?
Suppose we have two PHP files, file1.php and file2.php. The file1.php contains the following code:
include_once('file2.php');
echo "This is file1.php.";
?>
And file2.php includes the following code:
echo "This is file2.php.";
?>
If you execute file1.php, it will include file2.php using the include_once() function. Since file2.php has not been included before, it will be loaded and its contents will be executed.
If you execute file1.php again, it won’t load the file2.php again since it’s already loaded in the file. This is how include_once() function works.
Example
Let’s consider we have created two PHP files. The first file is file.php which is used to be included.
The second PHP file is index.php which is used to include file.php.
include_once('file.php');
include_once('file.php');
?>
You can see here, the above-mentioned file file.php is included twice in the index.php file using the include_once() function. But, the inclusion’s second instance is omitted because the include_once() function rejects all the same inclusions after the first one.
Output
Conclusion
PHP’s include_once() function is useful for developers to avoid errors caused by duplicate code or conflicting functions, while also improving the organization and performance of their PHP code. By understanding its syntax, parameters, and practical usage examples, developers can take full advantage of this function and streamline their PHP projects.