To make your code more readable, you can place your functions in a separate file. PHP provides include and include_once functions that enable you to insert code from other files.
You can name your include file anything you like, but you should always use the .php extension because if you name them something else, such as .inc, it's possible that a user can request the .inc file and the Web server will return the code stored in it.
include and include_once provide a warning if the resource cannot be retrieved and tries to continue execution of the program.
The include statement allows you to include and attach other PHP scripts to your own script. You can think of it as simply taking the included file and inserting it into your PHP file.
Here is add.php that is used to include in another script.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <head> <title>PHP</title> <meta Name="Author" Content="Hann So"> </head> <body> <p> <?php function add($x, $y) { return $x+$y; } ?> </p> </body> </html> |
Below is using the include function.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <head> <title>PHP</title> <meta Name="Author" Content="Hann So"> </head> <body> <p> <?php include('add.php'); echo add(2,3); ?> </p> </body> </html> |
A problem may arise when you include many nested PHP scripts because the include statement does not check for scripts that have already been included. For example if you did as below, you'd get an error.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <head> <title>PHP</title> <meta Name="Author" Content="Hann So"> </head> <body> <p> <?php include('add.php'); include('add.php'); echo add(2,3); ?> </p> </body> </html> |
To avoid this type of error, you should use the include_once statement.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN"> <head> <title>PHP</title> <meta Name="Author" Content="Hann So"> </head> <body> <p> <?php // You are not going to place the same include_once statements right next to each other. // It's possible that you may include a file, which includes another file. include_once('add.php'); include_once('add.php'); echo add(2,3); ?> </p> </body> </html> |