1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
<?php namespace amekusa\plz; main::required;
/**
* Constant utilities
*
* To get started, place the following line around top of your code.
* ```php
* use amekusa\plz\constant;
* ```
*/
abstract class constant {
/**
* Returns the value of constant:`$X`
*
* If the constant is undefined, returns the 2nd argument.
* Additionally, if the 3rd is `true`, defines constant:`$X` of which value is the 2nd.
*
* @example Demonstration
* ```php
* define('CONST_X', 'I am CONST_X.');
* define('CONST_Y', 'I am CONST_Y.');
* var_dump( constant::get('CONST_X') );
* var_dump( constant::get('CONST_Y') );
* var_dump( constant::get('CONST_Z') ); // Alternates with NULL
* var_dump( constant::get('CONST_Z', 'No such constant!') ); // Alternates with a string
* ```
* ```php
* string(13) "I am CONST_X."
* string(13) "I am CONST_Y."
* NULL
* string(17) "No such constant!"
* ```
* @example Just-in-Time `define()`
* ```php
* define('CONST_X', 'I am CONST_X.');
* define('CONST_Y', 'I am CONST_Y.');
* var_dump( constant::get('CONST_X') );
* var_dump( constant::get('CONST_Y') );
* var_dump( constant::get('CONST_Z', 'I am CONST_Z.', true) );
* echo 'Hi, ' . CONST_X . "\n";
* echo 'Hi, ' . CONST_Y . "\n";
* echo 'Hi, ' . CONST_Z . "\n";
* ```
* ```php
* string(13) "I am CONST_X."
* string(13) "I am CONST_Y."
* string(13) "I am CONST_Z."
* Hi, I am CONST_X.
* Hi, I am CONST_Y.
* Hi, I am CONST_Z.
* ```
* @param string $X The name of a constant
* @param mixed $Alt *(optional)* The alternative value to return if constant:`$X` is undefined
* @param boolean $Defines *(optional)* Whether or not to define constant:`$X` if it is undefined
* @return mixed The value of constant:`$X` or `$Alt`
*/
static function get($X, $Alt = null, $Defines = false) {
if (defined($X)) return constant($X);
if ($Defines) define($X, $Alt);
return $Alt;
}
}