What is the difference between define () and const?

8

What is the difference between declaring constants with define() or with const .

Would it be the same or are there any details that I should know about?

define('TESTE', 'constante 1');
const TESTE2 = 'constante 2';

echo TESTE . '<br>' . TESTE2;
    
asked by anonymous 04.01.2015 / 19:17

2 answers

9

Both can be used to define global constants for the application.

  • const sets the compile-time constant, which tends to be much better.

    It can also be used to define class scoped counters, which is also much better.

    Because it can not be defined at runtime, it can not be created conditionally as is possible with define . There is a programming technique (bad, in my opinion) that benefits from the existence or not of constants.

    Obviously some expressions are not possible in the definition of a const , only what can be solved at compile time.

    Since the name of a const must be set at compile time, the name can not be generated from some expression.

    The name is case sensitive since it is a symbol of language.

    It is faster to access a real constant than an element of a dictionary.

    It's elegant, it's just like other languages do, it looks right, it's more readable, it causes less confusion.

  • define defines the run-time constant. In the background it creates a key in a dictionary to store a value.

Whenever possible I prefer const . And to speak the truth is always possible. For me define stayed as a legacy. Only in version 5.3 of PHP const can be used to define global constants. But as the ideal is not to define anything global, without at least having a scope, it made no difference.

Documentation for const and define .

    
04.01.2015 / 19:23
4

This was answered in this question here: link

But the general point is that until PHP 5.3 you could not use const within the global scope, it was restricted to object scopes (a class for example). It served to define a local constant variable within the scope of this object.

The define has the same purpose, but it can only be used in global scope, and its use should be only to set global settings that will affect the application as a whole.

The examples of const and define vary widely, for example, const can be used within a math class to store the value of a number pi, for example, since it will only be allocated when the code compiles.

define can be used to set a global parameter of the application, a skin for example, or some system configuration that needs to be read by the entire code. Since it is created at runtime you will have no problems if the code does not go through that part.

    
04.01.2015 / 19:25