include_once()

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 often results in repeated declarations 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 behaves the same way as include() the first time it's called. However, if include_once() is called again for the same file during script execution, the file is not 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 hard-code 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 move your project to a new server, you might 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/ 

The include_path can include as many directories as you want, separated by colons (semicolons in Windows). The first dot (.) before the first colon indicates "current directory." You can then reference your library file by only its name:

 include_once("mylib.inc.php"); 

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

graphics/book.gif

PHP has both a require() statement, which performs a similar function to include(), and a require_once() statement. require() is executed regardless of a script's flow, and therefore shouldn't be used as part of conditional or loop structures.

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




Sams Teach Yourself PHP, MySQL and Apache in 24 Hours
Sams Teach Yourself PHP, MySQL and Apache in 24 Hours
ISBN: 067232489X
EAN: 2147483647
Year: 2005
Pages: 263

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net