Can I use the define () command to set a numeric value to a constant? All the examples I've tried only use strings, is it okay to set a numeric value?
Can I use the define () command to set a numeric value to a constant? All the examples I've tried only use strings, is it okay to set a numeric value?
The use of constants helps to avoid the problem of magic numbers which is the repetition of a value in several statement that does not make much sense, instead of face occurrence is exchanged for a constant.
An example is number 7, maybe the first thing that comes to mind are the days of the week and how about 86,400 what is the meaning? these two numbers can be exchanged for constants
define('DIAS_DA_SEMANA', 7);
define('DIA_EM_SEGUNDOS', 86400);
Until the php5.5 constants were only supported with scalar values (string, int, double, bool) no operation (concatenation) could be made.
php5.6 introduced a new feature called scalar constants where you can define the value of a constant through expressions, function calls, operation and also allows you to define it as an array.
define('ano', 2015); //valida em todas as versões;
define('ano', date('Y')); //valida a partir da versão 5.6
Reading recommends:
Practical use of Constant scalar expressions in PHP and other languages
What are the advantages and disadvantages of declaring constants as an array?
You can, yes, even PHP uses some numbers in constants such as error level constants.
echo E_ALL;
echo PHP_EOL;
echo E_NOTICE;
echo PHP_EOL;
echo E_DEPRECATED;
echo PHP_EOL;
echo M_PI; // Constante matemática PI
Output:
32767
8
8192
3.1415926535898