6

What are the best practices for usage of PHP’s Magic Constants, such as __LINE__ , __FILE__, __FUNCTION__, __CLASS__ and __METHOD__?

For example I use __LINE__ and __CLASS__ to locate the SQL Error like this :

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

Is this an acceptable practice?

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Amirouche Douda
  • 1,564
  • 1
  • 21
  • 30

3 Answers3

2

The practice you show has two shortcomings:

  • You are not showing the file the error occurs in - you'd have to have a very strict file structure that maps classes to files 1:1 for this to be useful

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

Other than that, using these constants is perfectly 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

Paul DelRe
  • 4,003
  • 1
  • 24
  • 26
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
1

The purpose for 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__)).

Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144
1

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

Stephen
  • 18,827
  • 9
  • 60
  • 98