PHP – Constants Defined

0 0
Read Time:1 Minute, 21 Second

PHP – Constants Defined

PHP Constant Variable
  • A constant is an identifier (name) for a simple value. That value cannot change during the execution of the PHP script. Constants are case-sensitive. By convention, constant identifiers are always uppercase.
  • The name of a constant follows the same rules as any label in PHP. A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores,PHP constants should be defined in uppercase letters. 

Note:

Prior to PHP 8.0.0, constants defined using the define() function may be case-insensitive.

PHP constants can be defined by 2 ways:

  • Using define() function
  • Using const keyword

PHP constant: define() function

Syntax:

 define(name, value)
  • name: It specifies the constant name.
  • value: It specifies the constant value..

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

<?php
 define("MESSAGE","HELLO CodeDixa");
 echo MESSAGE;
?>

Output:

HELLO CodeDixa

PHP constant: const keyword

  • PHP introduced a keyword const to create a constant.
  • The const keyword defines constants at compile time.
  • It is a language construct, not a function. 
  • The constant defined using const keyword are case-sensitive.

Example:

<?php
 const MESSAGE="Hello const by CodeDixa PHP";
 echo MESSAGE;
?>

Output:

Hello const by CodeDixa PHP

constant() function

There is another way to print the value of constants using constant() function instead of using the echo statement.

Syntax:

constant(name);

Example:

<?php 
 define("MSG","Welcome to CodeDixa");
 echo MSG."<br>";
  //or
 echo constant("MSG");
 //both are smiliar
?>

Output:

Welcome to CodeDixa
Welcome to CodeDixa
Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

Average Rating

5 Star
0%
4 Star
100%
3 Star
0%
2 Star
0%
1 Star
0%

One thought on “PHP – Constants Defined

  1. Wow, fantastic blog structure! How long have you ever been running a blog for?
    you make blogging glance easy. The total glance of your site is great, as well as the content!

Leave a Comment