How to include files with PHP

by on September 28, 2006 · 0 comments· LAST UPDATED September 29, 2006

in

Q. How do you include files with PHP?

A. PHP has a special function called include().The include() statement includes and evaluates the specified file.

Foe example if you have a file called lib.php:
<?php
function test(){
echo "test() called";
}
?>

Now you can include lib.php and call test() from demo.php:
<?php
include("lib.php");
test();
?>

Files for including are first looked in include_path relative to the current working directory and then in include_path relative to the directory of current script. E.g. if your include_path is ., current working directory is /www/, you included include/a.php and there is include "b.php" in that file, b.php is first looked in /www/ and then in /www/include/. If filename begins with ./ or ../, it is looked only in include_path relative to the current working directory.

When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.

Read php include help page for more information.

TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 0 comments… add one now }

Leave a Comment

Tagged as:

Previous Faq:

Next Faq: