Constants can be defined using the const keyword, or by using the define() function. While define() allows a constant to be defined to an arbitrary expression, the const keyword has restrictions.

Constants have a global scope by default. It's recommended to use uppercase names for constants.


define()

define("PI", 3.14159);
define("APP_NAME", "My Application");

You can define constants dynamically (using a variable as the name):

$name = "VERSION";
define($name, "1.0.0");

echo VERSION; // 1.0.0

Works only in the global scope (not inside classes).


const keyword

const PI = 3.14159;
const APP_NAME = "My Application";

Constants are defined at compile-time (not runtime).

You cannot use dynamic names:

$name = "VERSION";
const $name = "1.0.0"; // Parse error

Can be used inside classes and interfaces:

class Config
{
    const VERSION = "1.0.0";
    const DEBUG = true;
}

echo Config::VERSION; // 1.0.0

Differences: define() vs const

When defined:

  • define(): Runtime (execution time);
  • const: Compile time;

Scope:

  • define(): Global only;
  • const: Global and inside classes/interfaces;

Dynamic names:

  • define(): Supported;
  • const: Not supported;

Performance:

  • define(): Slightly slower (runtime);
  • const: Faster (compile-time);

Magic Constants

There are a few magical constants that change depending on where they are used. For example, the value of __LINE__ depends on the line that it's used on in a script. All these "magical" constants are resolved at compile time, unlike regular constants, which are resolved at runtime. These special constants are case-insensitive and are as follows:

  • __LINE__ The current line number of the file.
  • __FILE__ The full path and filename of the file with symlinks resolved.
  • __DIR__ The directory of the file.
  • __FUNCTION__ The function name, or {closure} for anonymous functions.
  • __CLASS__ The class name.
  • __TRAIT__ The trait name.
  • __METHOD__ The class method name.
  • __PROPERTY__ Only valid inside a property hook. It is equal to the name of the property.
  • __NAMESPACE__ The name of the current namespace.
  • ClassName::class The fully qualified class name.

Source: Orkhan Alishov's notes