PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 5 ■ OBJECT TOOLS

■Note require() and require_once() are actually statements, not functions. This means that you can omit


the brackets when using them. Personally, I prefer to use brackets anyway, but if you follow suit, be prepared to


be bored by pedants eager to explain your mistake.


Figure 5–1 shows the util and business packages from the point of view of the Nautilus file
manager.


Figure 5–1. PHP packages organized using the file system


■Note require_once() accepts a path to a file and includes it evaluated in the current script. The function will


only incorporate its target if it has not already been incorporated elsewhere. This one-shot approach is particularly


useful when accessing library code, because it prevents the accidental redefinition of classes and functions. This


can happen when the same file is included by different parts of your script in a single process using a function like


require() or include().


It is customary to use require() and require_once() in preference to the similar include() and


include_once() functions. This is because a fatal error encountered in a file accessed with the require()


functions takes down the entire script. The same error encountered in a file accessed using the include()


functions will cause the execution of the included file to cease but will only generate a warning in the calling


script. The former, more drastic, behavior is safer.


There is an overhead associated with the use of require_once() when compared with require(). If you need to


squeeze every last millisecond out of your system you may like to consider using require() instead. As is so often


the case, this is a trade-off between efficiency and convenience.

Free download pdf