Tuesday, June 17, 2008

PHP script include() function

One of the things I regard best as a developer, is the include() function of PHP.

include() is something like the MasterPages and ContentPages in ASP.NET. You can use it for defining site-wide variables and constants, defining functions and classes, or even putting site-wide processes and functions into it and call it from anywhere else.

For example, i need to display "hello world" on both "a.php" and "b.php" pages. I can use the include() function to do this. first, i put
<?php echo "hello world"; ?>
into "head.php", then i put
<?php include('head.php'); ?>
into both pages "a.php" and "b.php". Then, both pages "a.php" and "b.php" will show up "hello world".

both pages will run "head.php" at the line where include() function is. However, there are some unexpected results of using include().

For example, i put "head.php" into a folder call "folder", and i have this script "call.php" which have the following
<?php include('folder/head.php'); ?>
The current directory for "head.php" is no longer 'folder/', but it is now '/', since it is called by "call.php". Included scripts will always use the current directory of the parent script. (See more: Directory Functions and chdir() function)

The return statement can be used in the main scope of included scripts to return the control back to the parent script immediately. example:
<?php return; $I++; ?>
variable $I will not be incremented. but if you run this code as parent main scope, return will not work.


anonymephilo said...

In effect, include() doesn't call the file, but copy/paste (sort of) the contents of the target file where you put the include() statement.
Thus, the observed result.
Also, require() is useful when a resource present in the target file is absolutely needed and the page should not display if it is not present [require() will return a fatal error, include() will return only a warning].



thephpdeveloper said...

yep anonymephilo. that's very true.
guess i didn't elaborate on that =D

Muhammad Azeem said...

This is a nice article..
Its easy to understand ..
And this article is using to learn something about it..

c#, dot.net, php tutorial, Ms sql server

Thanks a lot..!