include_once and require_once
Learn to include a file only once with include_once and require_once.
include_once and require_once
include_once and require_once make sure the same file is included only once. PHP keeps a list of already included files; on the second call the file is skipped.
This matters for files that define functions or classes. If you include a functions.php from two places, PHP raises a fatal error because the functions are declared twice. include_once removes this risk. require_once does the same with a fatal-error guarantee: if the file is missing on the first call the script stops, and on the second call it is skipped.
Function collisions and _once
If you include a file twice and that file declares a function, PHP raises the 'Cannot redeclare function' fatal error. The same function cannot be defined twice.
This is where include_once and require_once help: PHP tracks whether the file has already been included and runs it only on the first call. This lets you safely include files that hold function or class declarations from many places. Most autoloaders and composer packages use require_once, which is why this statement shows up a lot in OOP and library code.
Exercise include_once counter.php twice
Assign the path sys_get_temp_dir() . "/counter.php" to $file. Write the file with file_put_contents($file, "<?php echo 'Once'; ?>"). Then write the call include_once $file; twice on separate lines. The output should show 'Once' only once.
Show example solution
First set $file = sys_get_temp_dir() . "/counter.php";. Then write file_put_contents($file, "<?php echo 'Once'; ?>");. Finally add the include_once $file; line twice on separate lines.
Example solution:
<?php
// Create counter.php and include_once it twice
$file = sys_get_temp_dir() . "/counter.php";
file_put_contents($file, "<?php echo 'Once'; ?>");
include_once $file;
include_once $file;
Test yourself
-
Include once
include_____ 'utils.php';Show answer
include_once 'utils.php'; -
What happens if you call include_once on the same file twice?
- The file runs twice, output doubles
- PHP raises a fatal error
- The file runs only once
- The file is ignored, never runs
Show answer
The file runs only once — Correct. include_once includes the same file only once; the second call is skipped.
-
Match statements to their behaviors
- include
- Warns when file missing
- require
- Stops when file missing
- include_once
- Includes once, warns
- require_once
- Includes once, stops