PHP require

Summary: in this tutorial, you will learn how to use the PHP require construct to load the code from a file into the current script.

Introduction to the PHP require construct

PHP require construct loads the code from an file into a script and executes that code. The following shows the syntax of the require construct:

<?php

require 'path_to_file';Code language: HTML, XML (xml)

To load the code from a file, you specify the file path after the require keyword. When loading the file, the require construct executes the code in the loaded file.

The require construct is the same as the include construct except that if it fails to load the file, it’ll issue a fatal error and halt the script, whereas the include construct only issues a warning and allows the script to continue.

In practice, you often use the require construct to load the code from libraries. Since the libraries contain the required functions to execute the script, it’s better to use the require construct than the include construct.

PHP require example

Suppose that you have index.php and functions.php, and you want to load the functions.php to the index.php file.

The functions.php file has one function called dd(), which stands for the dump and die because it uses both var_dump() and die() functions:

<?php

if (!function_exists('d')) {
	function dd($data)
	{
		echo '<pre>';
		var_dump($data);
		echo '</pre>';
		die();
	}
}Code language: HTML, XML (xml)

The index.php will look like this:

<?php

require 'functions.php';

dd([1, 2, 3]);Code language: HTML, XML (xml)

In this file, we use the require construct to load the code in functions.php that defines the dd() function if the function doesn’t exist. Then, we use dd() function defined in the functions.php.

PHP require is not a function

Sometimes, you see the following code:

<?php

require('functions.php');Code language: HTML, XML (xml)

The code looks like a function call because of the parentheses (). and it works.

However, the parentheses are not a part of the require construct. Instead, they belong to the file path expression that is being loaded.

PHP require_once

PHP require_once is the counterpart of the include_once except that the require_once issues an error if it fails to load the file. Also, the require_once won’t load the file again if the file has been loaded.

Here’s the syntax of require_once construct:

<?php

require_once 'path_to_file';Code language: HTML, XML (xml)

Summary

  • Use require construct to load the code from another file into the script.
  • Use require_once construct to load the code from another file once and won’t include the file again if the file has been loaded.
  • The require and require_once are language constructs, not functions.
Did you find this tutorial useful?