There are a number of constants automatically set for you by PHP in order to save you having to recalculate complicated values each time in your script, but it also provides other helpful information. For example, PHP always sets the __FILE__, __LINE__, __FUNCTION__, __CLASS__, and __METHOD__ constants for you - note that those are double underscores on either side to make it unlikely you will want to use them for your own constants.
These five pre-set constants give you the following:
__FILE__ |
The script filename being parsed. Note that this reports the file that contains the current line of code, so this will report the name of an include file if used therein. |
__LINE__ |
The line number PHP is executing |
__FUNCTION__ |
The name of the function PHP is currently inside |
__CLASS__ |
The name of the class of the object being used |
__METHOD__ |
The name of the class function PHP is currently inside |
Using these special constants, it is very easy to output complex error reports or other debugging information.
PHP defines a large variety of constants for use in its functions and extensions - a great many of these are outlined elsewhere in this book, and they generally help you remember values. For example, if you want to know the value of the mathematical figure Pi, use M_PI, which is much easier than remembering 3.141592654. To extract variables from an array and always use a prefix, use EXTR_PREFIX_ALL - again, much easier to remember than a numerical value such as 3, but does the same thing.
There are some generic coding constants that you might find useful, such as PHP_EOL to grab the new-line character for the current OS (helps make your script portable), PHP_OS to grab the name of the OS, PHP_VERSION to get the version number of the engine, and DEFAULT_INCLUDE_PATH to see where PHP might include files from if it can't find them in the local directory.
There are pre-defined constants to do all sorts of things inside your code, and there just is not room to cover them all here. For a comprehensive and up to date list, check the PHP manual at http://www.php.net/manual/en/reserved.constants.php .
Want to learn PHP 7?
Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!
If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!
Next chapter: Operators >>
Previous chapter: Constants
Jump to:
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws.