11/14/2016 - note updated by sobak
-----
CONSTANTS and PHP Class Definitions
Using "define('MY_VAR', 'default value')" INSIDE a class definition does not work as expected. You have to use the PHP keyword 'const' and initialize it with a scalar value -- boolean, int, float, string (or array in PHP 5.6+) -- right away.
<?php
define('MIN_VALUE', '0.0'); define('MAX_VALUE', '1.0'); class Constants
{
const MIN_VALUE = 0.0; const MAX_VALUE = 1.0; public static function getMinValue()
{
return self::MIN_VALUE;
}
public static function getMaxValue()
{
return self::MAX_VALUE;
}
}
?>
#Example 1:
You can access these constants DIRECTLY like so:
* type the class name exactly.
* type two (2) colons.
* type the const name exactly.
#Example 2:
Because our class definition provides two (2) static functions, you can also access them like so:
* type the class name exactly.
* type two (2) colons.
* type the function name exactly (with the parentheses).
<?php
$min = Constants::MIN_VALUE;
$max = Constants::MAX_VALUE;
$min = Constants::getMinValue();
$max = Constants::getMaxValue();
?>
Once class constants are declared AND initialized, they cannot be set to different values -- that is why there are no setMinValue() and setMaxValue() functions in the class definition -- which means they are READ-ONLY and STATIC (shared by all instances of the class).