PHP Constant

In PHP, constant is an identifier or a name for a fixed value in a program. A constant value cannot modify during the implementation of the script. Constant are same like variables except that one they are defined, they cannot be undefined or modified (except the magic constants).

phpconstant

Constants are very helpful for saving the data that don’t vary while the script is executing. Common examples of such data comprise configuration settings such as database passwords and username, company name, website’s URL, etc.

PHP constants can be categorized in two ways:

  • Using define() function
  • Using const keyword

PHP constants follow the same rules as PHP variable rules. For instance, it can be initiated with a letter or underscore only. Usually, PHP constants should be expressed in the uppercase letters.

PHP define()

Let’s see the syntax of define() function in PHP.

define(name, value, case-insensitive)

name: shows the constant name

value: show the constant value

case-insensitive: Its default value is false. It signifies that it is case sensitive by default.

Let’s see the example to define the PHP constant using define().

Example 1:

<?php 

define(“MESSAGE”,“Hello PHP”);

echo MESSAGE;

?> 

Output:  Hello PHP

……………………………………………………………………

Example 2:

<?php

define(“MESSAGE“,“Hello PHP”,true); //not case sensitive

echo MESSAGE;

echo message;

?>

Output: Hello PHP Hello PHP

…………………………………………………………………….

Example 3:

<?php

define(“MESSAGE”,”Hello PHP”,false); //case sensitive

echo MESSAGE;

echo message;

?>

Output: Hello PHP

Notice: Use of undefined constant message – assumed ‘message’

in C:\wamp\www\vconstant3.php on line 4

message

…………………………………………………………………….

PHP constant: const keyword

The const keyword shows constants at running time. It is a kind of language constructs not any function.

It is a bit quicker than define().

It is always used as case sensitive.

Example:

<?php 

const MESSAGE=”Hello const by JavaTpoint PHP”;

echo MESSAGE;

?>

Output: Hello const by JavaTpoint PHP

…………………………………………………………………….

onTime It Solution

onTime IT Solution always happy to serve you in Information Technology (IT). Learn HTML, CSS, Javascript, PHP, Android, Digital Marketing, Latest IT News and many more.

Leave a Reply

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