Numerical value definition in PHP Constants

Asked

Viewed 75 times

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?

  • can give an example?

  • define('CONSTANT', 1); i always find examples of type define('CONSTANT', 'string')

  • 1

    Yes, it is good practice to avoid magic numbers.

2 answers

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

Example - ideon

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?

What is the difference between define() and const

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

You are not signed in. Login or sign up in order to post.