Blog de programación, errores, soluciones

Chose Language:
Author: Admin/Publisher |finished | checked

PHP include and require

Both include and require statements are used to include the entire text from one file into another, but they have a difference in behavior. The include statement will produce a warning if the file is not found, while the require statement will produce a fatal error.

Sintaxis / Sintax
Sintaxis / Sintax

Include and include_once example

I will first create a file home.php to show how include works and home2.php to show the functionality of include_once.

echo "home"; // imprimirá home
echo "home2";// imprimirá home2

Now we will make some proves with include and include_once

include "home.php";
//include home.php; //will not work
include_once "home2.php";//make sure it's included only once
include_once("home2.php");//home2.php will not be included since it's already included

Require and require_once example

require: Essentially, require indicates that the file is required, which brings in all the code inside the file that is within require(""); or require "";

require_once: indicates that the file is required only once.

We will use the same home and home2 files for this example.

require "home.php";
//require home.php; //will not work
require_once "home2.php";//ensures that it is included only once


Category: en-php
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category