You want to define constants on a per-class basis, not on a global basis.
Define them like class properties, but use the const label instead:
1 2 3 4 5 6 |
class Math { const pi = 3.14159; // universal const e = 2.71828; // constants } $area = math::pi * $radius * $radius; |
PHP reuses its concept of global constants and applies them to classes. Essentially, these are final properties.
Declare them using the const label:
1 2 3 4 5 6 |
class Math { const pi = 3.14159; // universal const e = 2.71828; // constants } $area = math::pi * $radius * $radius; |
Like static properties, you can access constants without first instantiating a new instance of your class, and they’re accessed using the double colon (::) notation.
Prefix the word self:: to the constant name to use it inside of a class. Unlike properties, constants do not have a dollar sign ($) before them:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class Circle { const pi = 3.14159; protected $radius; public function __construct($radius) { $this->radius = $radius; } public function circumference() { return 2 * self::pi * $this->radius; } } $c = new circle(1); print $c->circumference(); |
This example creates a circle with a radius of 1 and then calls the circumference method to calculate its circumference:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
define('pi', 10); // global pi constant class Circle { const pi = 3.14159; // class pi constant protected $radius; public function __construct($radius) { $this->radius = $radius; } public function circumference() { return 2 * pi * $this->radius; } } $c = new circle(1); print $c->circumference(); |
Oops! PHP has used the value of 10 instead of 3.14159, so the new answer is 20 instead of 6.28318.
Although it’s unlikely that you will accidentally redefine π (you’ll probably use the builtin M_PI constant anyway), this can still slip you up.
You cannot assign the value of an expression to a constant, nor can they use information passed into your script:
1 2 3 4 5 6 7 8 9 10 11 |
// invalid class permissions { const read = 1 << 2; const write = 1 << 1; const execute = 1 << 0; } // invalid and insecure class database { const debug = $_REQUEST['debug']; } |
Neither the constants in permissions nor the debug constant in database are acceptable because they are not fixed. Even the first example, 1 << 2, where PHP does not need to read in external data, is not allowed.
Because you need to access constants using an explicit name, either self:: or the name of the class, you cannot dynamically calculate the class name during runtime. It must be declared beforehand. For example:
1 2 3 4 5 6 7 8 9 |
class Constants { const pi = 3.14159; // rest of class here } $class = 'Constants'; print $class::pi; |
This produces a parse error, even though this type of construct is legal for nonconstant expressions, such as $class->pi.