What is the difference between define() and const?

Asked

Viewed 2,447 times

12

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

Would it be the same thing or have some detail I should know?

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

echo TESTE . '<br>' . TESTE2;

2 answers

10


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

  • const defines the constant at compile time, which is usually much better.

    It can also be used to define constants with class scope, which is also much better.

    Since it is not possible to define it at runtime, it cannot 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.

    Like the name of a const must be defined at compile time, the name cannot be generated from some expression.

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

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

    It’s elegant, it’s like other languages do, it feels right, it’s more readable, it causes less confusion.

  • define sets the constant at runtime. At the bottom it creates a key in a dictionary to store a value.

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

Documentation of const and define.

  • Interesting! I was going to ask this question. I see many projects, for recent versions of PHP, with a lot of call to define. I think it’s even better for code organization

6

That was answered in this question here: https://stackoverflow.com/questions/2447791/define-vs-const

But the general thing is that even PHP 5.3 you couldn’t 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 the use of it should only be to set global settings that will affect the application as a whole.

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

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

Browser other questions tagged

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