To use your code across many PHP scripts, PHP provides four expressions to load an external script:
include
If you want to reuse a function in more than one script, you can store it in a file and then use one of the above-mentioned expressions to include that function in your desired scripts. For example, you can create a file called functions.php
and put the function/code in the file:
<?php # functions.php function doublevalue($var) { return $var * 2; }
In a script, you can then use the include
statement to provide access to the function doublevalue()
:
<?php # testing.php include "functions.php"; echo doublevalue(10); # Prints: 20
The script works as before, but the function doublevalue()
can now be reused across several scripts by including functions.php
file.
The include
statement is treated in the same way as other statements. For example, you can conditionally include different files using the following code fragment:
<?php $post = $_POST['submit'] ?? ""; if ($post == "") { include "form.php"; } else { include "verify.php"; }
Any PHP code in an include file must start with the PHP start tag. The PHP script engine treats the contents of include files as HTML unless script tags are used.
Include_once
Be careful when using the include
statement. Including the same file twice or declaring a function in the script that is already in an include file causes PHP to complain about the function being redefined, consider the following example:
<?php # testing.php //Including twice functions.php include "functions.php"; include "functions.php"; echo doublevalue(10); /* Fatal error: Cannot redeclare doublevalue() (previously declared in ... functions.php:2 */
It is recommended to use include_once
and require_once
because these directives first check whether the file has already been loaded before either will load a given script, consider the same example using include_once directive:
<?php # testing.php //Including twice functions.php include_once "functions.php"; include_once "functions.php"; echo doublevalue(10); # Prints: 20
The above code will not print any error.
require
The require
is identical to include
except upon failure it will also produce a fatal level error and halt the script whereas include
only emits a warning which allows the script to continue.
<?php include 'fakefile.php'; echo 'Hello world'; # Warning: include(fakefile.php): Failed to open stream # Hello world require 'fakefile.php'; echo 'Hello world again'; # not prints # Fatal error: Uncaught Error: Failed opening required 'fakefile.php'
require_once
The require_once
expression is identical to include_once
except upon failure it will produce a fatal level error and stop the script whereas include_once
only emits a warning which allows the script to continue.
User-defined functions: