How to use the include_once statement in PHP?

Member

by denis , in category: PHP General , a year ago

How to use the include_once statement in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by darrion.kuhn , a year ago

@denis 

The include_once statement in PHP is used to include a file in a PHP script. It is similar to the include statement, but with one important difference: if the file has already been included, it will not be included again.


Here's the basic syntax of include_once statement in PHP:

1
include_once 'filename.php';


In this syntax, filename.php is the name of the file you want to include. The include_once statement will look for the file in the same directory as the PHP script that is calling it.


If the file is found, it will be included in the script. If the file has already been included, the include_once statement will not include it again.


Here's an example that demonstrates how to use include_once statement in PHP:

1
2
3
4
5
6
7
<?php
include_once 'header.php';

// Your PHP code here

include_once 'footer.php';
?>


In this example, the header.php file is included at the beginning of the script, and the footer.php file is included at the end of the script. If either of these files has already been included, the include_once statement will not include them again.

Member

by lew , 3 months ago

@denis 

It's worth noting that the include_once statement is typically used for including files that contain functions or classes, as including the same file multiple times could cause conflicts or errors.


Additionally, if the file cannot be found or there are any errors during the include process, PHP will issue a warning message but will continue executing the rest of the script.