[php] define() vs. const

In PHP, when do you use

define('FOO', 1);

and when do you use

const FOO = 1;

?

What are the main differences between those two?

This question is related to php constants

The answer is


Most of these answers are wrong or are only telling half the story.

  1. You can scope your constants by using namespaces.
  2. You can use the "const" keyword outside of class definitions. However, just like in classes the values assigned using the "const" keyword must be constant expressions.

For example:

const AWESOME = 'Bob'; // Valid

Bad example:

const AWESOME = whatIsMyName(); // Invalid (Function call)
const WEAKNESS = 4+5+6; // Invalid (Arithmetic) 
const FOO = BAR . OF . SOAP; // Invalid (Concatenation)

To create variable constants use define() like so:

define('AWESOME', whatIsMyName()); // Valid
define('WEAKNESS', 4 + 5 + 6); // Valid
define('FOO', BAR . OF . SOAP); // Valid

With define keyword constant, you will get the facilities of case insensitive but with const keyword you did not.

define("FOO", 1, true);
echo foo; //1
echo "<br/>";
echo FOO; //1
echo "<br/>";

class A {
  const FOO = 1;
}

echo A::FOO; //valid
echo "<br/>";

//but

class B {
  define FOO = 1; //syntax error, unexpected 'define'
}

echo B::FOO; //invalid

No one says anything about php-doc, but for me that is also a very significant argument for the preference of const:

/**
 * My foo-bar const
 * @var string
 */
const FOO = 'BAR';

I know this is already answered, but none of the current answers make any mention of namespacing and how it affects constants and defines.

As of PHP 5.3, consts and defines are similar in most respects. There are still, however, some important differences:

  • Consts cannot be defined from an expression. const FOO = 4 * 3; doesn't work, but define('CONST', 4 * 3); does.
  • The name passed to define must include the namespace to be defined within that namespace.

The code below should illustrate the differences.

namespace foo 
{
    const BAR = 1;
    define('BAZ', 2);
    define(__NAMESPACE__ . '\\BAZ', 3);
}

namespace {
    var_dump(get_defined_constants(true));
}

The content of the user sub-array will be ['foo\\BAR' => 1, 'BAZ' => 2, 'foo\\BAZ' => 3].

=== UPDATE ===

The upcoming PHP 5.6 will allow a bit more flexibility with const. You will now be able to define consts in terms of expressions, provided that those expressions are made up of other consts or of literals. This means the following should be valid as of 5.6:

const FOOBAR = 'foo ' . 'bar';
const FORTY_TWO = 6 * 9; // For future editors: THIS IS DELIBERATE! Read the answer comments below for more details
const ULTIMATE_ANSWER = 'The ultimate answer to life, the universe and everything is ' . FORTY_TWO;

You still won't be able to define consts in terms of variables or function returns though, so

const RND = mt_rand();
const CONSTVAR = $var;

will still be out.


Yes, const are defined at compile-time and as nikic states cannot be assigned an expression, as define()'s can. But also const's cannot be conditionally declared (for the same reason). ie. You cannot do this:

if (/* some condition */) {
  const WHIZZ = true;  // CANNOT DO THIS!
}

Whereas you could with a define(). So, it doesn't really come down to personal preference, there is a correct and a wrong way to use both.

As an aside... I would like to see some kind of class const that can be assigned an expression, a sort of define() that can be isolated to classes?


I believe that as of PHP 5.3, you can use const outside of classes, as shown here in the second example:

http://www.php.net/manual/en/language.constants.syntax.php

<?php
// Works as of PHP 5.3.0
const CONSTANT = 'Hello World';

echo CONSTANT;
?>

NikiC's answer is the best, but let me add a non-obvious caveat when using namespaces so you don't get caught with unexpected behavior. The thing to remember is that defines are always in the global namespace unless you explicitly add the namespace as part of the define identifier. What isn't obvious about that is that the namespaced identifier trumps the global identifier. So :

<?php
namespace foo
{
  // Note: when referenced in this file or namespace, the const masks the defined version
  // this may not be what you want/expect
  const BAR = 'cheers';
  define('BAR', 'wonka');

  printf("What kind of bar is a %s bar?\n", BAR);

  // To get to the define in the global namespace you need to explicitely reference it
  printf("What kind of bar is a %s bar?\n", \BAR);
}

namespace foo2
{
  // But now in another namespace (like in the default) the same syntax calls up the 
  // the defined version!
  printf("Willy %s\n", BAR);
  printf("three %s\n", \foo\BAR);  
}
?>

produces:

What kind of bar is a cheers bar? 
What kind of bar is a wonka bar?
willy wonka 
three cheers

Which to me makes the whole const notion needlessly confusing since the idea of a const in dozens of other languages is that it is always the same wherever you are in your code, and PHP doesn't really guarantee that.


To add on NikiC's answer. const can be used within classes in the following manner:

class Foo {
    const BAR = 1;

    public function myMethod() {
        return self::BAR;
    }
}

You can not do this with define().


define I use for global constants.

const I use for class constants.

You cannot define into class scope, and with const you can. Needless to say, you cannot use const outside class scope.

Also, with const, it actually becomes a member of the class, and with define, it will be pushed to global scope.


Until PHP 5.3, const could not be used in the global scope. You could only use this from within a class. This should be used when you want to set some kind of constant option or setting that pertains to that class. Or maybe you want to create some kind of enum.

define can be used for the same purpose, but it can only be used in the global scope. It should only be used for global settings that affect the entire application.

An example of good const usage is to get rid of magic numbers. Take a look at PDO's constants. When you need to specify a fetch type, you would type PDO::FETCH_ASSOC, for example. If consts were not used, you'd end up typing something like 35 (or whatever FETCH_ASSOC is defined as). This makes no sense to the reader.

An example of good define usage is maybe specifying your application's root path or a library's version number.