Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


What are const, define(), and constant() in PHP?


PHP has a unique ways of doing things and carrying out operations which is quite different from other scripting languages like JavaScript and Python. This shot shows you how PHP works with constants.

PHP and constants

A constant in PHP:

  • Is made global automatically after definition. They can be used anywhere in the code.
  • Has values that cannot be changed during the code execution.
  • Has names that should not start with the special character; they can only start with an underscore or letters.

How to use the define() function

To create constants you can use the define() function.




This function takes the following parameters:

  • name: Name of the constant to be made.
  • Value: The value to be assigned to the constant.
  • case-insensitive: Whether the the name should be case-insensitive or not. Defaults to false if not indicated.

The const keyword

This is a language construct rather than a function. It is meant to define a constant at the point of the compilation of code.

Constants declared with the const keyword have to be declared at points which they can be accessible to the piece of code which will need them. This simply means they are not like those declared with the define() function, which remain global no matter where they are declared.

The keyword const constants have to be declared in the global scope. Constants declared with this keyword are case-sensitive.


const example_const = 56;

With this declaration, example_const is now a constant with the value 56 that cannot change.

How to use the constant() function

For constants declared with the define() function and the const keyword, their values can be returned using the constant() function passing the name of the constant in quotes as an argument. Any constant can be used by just their names.

See the code below to understand better.

define("defined", "just a defined constant",true);
//true makes it not case sensitive
echo DEFINED ."<br>";
echo constant("defined")."<br>";

//using const
const tryconst = "A lot has happened";
echo tryconst."<br>";
echo constant("tryconst");



View all Courses

Keep Exploring