PHP – Constants

By | October 2, 2021
PHP - Constants

PHP – Constants

A constant is an identifier whose value keeps constant or does not change during the execution of your program. Unlike variables, these constants are mostly uppercase. It can be a combination of letters, numbers, and underscore but should always be started with a letter or underscore. Define function is used to create a constant, which takes some arguments.

Defining constant with Define() function

If you want to create a constant then define() function will help you. Also, this function allows you to check whether a constant has been defined or not by taking the name of the constant as an argument and return true or false to confirm the existence of the constant.

This define() function will take three parameters-

define(name_of_constant, value_of_constant, case_sensitive)

Case_sensitive value is false by default.

Syntax

<?php
define(“Name”, “Jacob”);
Echo Name;
?>

Output

Vamware

Jacob
If we consider using the third parameter to check how case sensitive parameter is used for the constant.

<?php
define(“Name”, “Jacob”, true);
Echo name; //small letter constant will be ignored if case_sensitive parameter is set true
?>

Output

Vamware

Jacob

Constant() function

This function is used to return a constant value. Like variables, constant values can also be called dynamically using the constant() function.

Syntax

<?php
define(“Name”,” Jacob”);
Echo Name;
Echo “<br>”;
Echo constant(“Name”);
?>

Output

Jacob

Jacob

How constants are different from Variables

  • Constant value remains the same until it is redefined and does not change over the course of the execution.
  • Constants are not defined using $ sign while it is a mandate for the variable.
  • Constants are global and can be called from anywhere within the program.
  • Constants are not defined using a single assignment, they are defined using define() function.

Constants are Global

Once a constant is defined you can access it even from a function that is defined outside.

Syntax

<?php
Define (“Name”,” Jacob”);
Function First()
{
Echo Name;
}
First();
?>

Output

Jacob

Predefined Constants

PHP has some pre-defined constants whose value can be changed depending on where we are using those constants.

Constant Name Description
_LINE_ Returns the current line of the file.
_FILE_ Returns the name and the complete path of the file.
_FUNCTION_ Returns the function name.
_CLASS_ Returns the class name.
_METHOD_ Returns the class method name.

People are also reading:

Leave a Reply

Your email address will not be published.