Trusted answers to developer questions

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

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

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.

Syntax

define(name,Value,case-insentive)

Parameters

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.

Example

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.

<?php
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");
?>

RELATED TAGS

php
Did you find this helpful?