Home > Articles > Programming > PHP

  • Print
  • + Share This
This chapter is from the book

include_once()

One of the problems caused by using multiple libraries within your code is the danger of calling include() twice on the same file. This can occur in larger projects when different library files call include() on a common file. Including the same file twice will often result in the repeated declaration of functions and classes, thereby causing the PHP engine great unhappiness.

The situation is saved by the include_once() statement. include_once() requires the path to an include file and will behave the same way as include() the first time it is called. If include_once() is called again for the same file during script execution, however, the file will not be included again.

This makes include_once() an excellent tool for the creation of reusable code libraries.

The include_path directive

Using include() and include_once() to access libraries can increase the flexibility and reusability of your projects. However there are still headaches to overcome. Portability in particular can suffer if you hardcode the paths to included files. Imagine that you create a 'lib' directory and reference it throughout your project:

include_once("/home/user/bob/htdocs/project4/lib/mylib.inc.php");

When you come to move your project to a new server you may find that you have to change a hundred or more include paths. You can escape this fate by setting the include_path directive in your php.ini file.

include_path .:/home/user/bob/htdocs/project4/lib/

include_path can include as many directories as you want separated by colons (semicolons in Windows). You can then reference your library file only by its name

include_once("mylib.inc.php");

When you move your project you will only need to change the include_path directive.

NOTE

PHP4 has a require() statement, which performs a similar function to include(). There is also a require_once() statement.

require() is executed regardless of a script's flow, and should not therefore be used as part conditional or loop structures.

A file included as a result of a require() statement cannot return a value.

  • + Share This
  • 🔖 Save To Your Account