2
Can I use the define() command to set a numeric value to a constant? All examples I searched only use strings, there is a problem in defining a numerical value?
2
Can I use the define() command to set a numeric value to a constant? All examples I searched only use strings, there is a problem in defining a numerical value?
2
The use of constants helps to avoid the problem of magic numbers which is the repetition of a value in various instruction that does not make much sense, in the place of expensive 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 what 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 php5.5 constants were only supported with scaler values(string, int, double, bool) no operation(concatenation) could be done.
php5.6 introduced a new feature called scalar constants where it is possible to define the value of a constant through expressions, function calls, operation and also allows defining 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?
1
Yes, even PHP uses some numbers in constants such as constant error levels.
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
Exit:
32767
8
8192
3.1415926535898
Browser other questions tagged php
You are not signed in. Login or sign up in order to post.
can give an example?
– rray
define('CONSTANT', 1); i always find examples of type define('CONSTANT', 'string')
– Raphael Henrique
Yes, it is good practice to avoid magic numbers.
– rray