Home » Web development » PHP » How to define constant in php

How to define constant in php

How to define constant in php

Constants in PHP

(1) A constant is a name or an identifier for a simple value. It is defined using the define function and it does not start with $ sign

Syntax
define(name, value, case-insensitive)

Parameters:
name: Specifies the name of the constant
value: Specifies the value of the constant
case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false

Example
<?php
define("DBNAME", TECH);
echo DBNAME;
?>

(2) A constant value cannot change during the execution of the script. By default, a constant is case-sensitive. By convention, constant identifiers are always uppercase. A constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. If you have defined a constant, it can never be changed or undefined.

(3) A constant differ from variable as variable value can be changed across the execution while constant value cannot

(4) Constant value are global across the execution.

<?php
define("DBNAME", TECH);
function checkdbname() {
print DBNAME;
}

checkdbname();
?>

(5) constant value are retrieved using constant() function or simply we can use echo

<?php
echo "DBNAME";
echo "constant(DBNAME);
?>

(6) PHP defined some predefined constants like LINE,FILE, CLASS

(7) You can define constant as arrays starting PHP 7 as

<?php

define("DB", [
"TECH",
"GO",
"EASY"
]);
echo DB[0];
?>

Hope you like post on How to define constant in php

Also Reads
How to run php file in windows
uses of PHP
first php program
https://en.wikipedia.org/wiki/PHP

See also  How to use if else condition in php

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top