Best Practices for Using PHP Magic Constants

What are the best practices for using PHP Magic Constants, such as __LINE__ , __FILE__ , __FUNCTION__ , __CLASS__ and __METHOD__ ?

For example, I use __LINE__ and __CLASS__ to search for SQL errors as follows:

 $result = mysql_query($query) or die("Error SQL line ".__LINE__ ." class ".__CLASS__." : ".mysql_error()); 

Is this an acceptable practice?

+6
php magic-constants
source share
3 answers

The practice you show has two drawbacks:

  • You do not show the file in which the error occurred: you must have a very strict file structure that maps classes to 1: 1 files so that this is useful

  • __CLASS__ will show you the wrong result if an error occurs in an inherited class. Use get_class($this) to get the current current class.

In addition, the use of these constants is quite acceptable. note that

  • __FUNCTION__ and __CLASS__ were added in PHP 4.3

  • __METHOD__ is available since PHP 5.0.0

  • __DIR__ and __NAMESPACE__ are available since PHP 5.3.

docs

+2
source share

The goal of these constants is debugging and logging. This is exactly what you are doing.

__FILE__ can also be used for relative file paths (e.g. dirname(__FILE__) ).

+1
source share

The only advice I can give is that not all magic constants are defined. Therefore, if in doubt, use if(defined('__MAGIC_CONSTANT__'))

+1
source share

All Articles