Skip to content
Related Articles

Related Articles

What are the differences between PHP constants and variables ?

Improve Article
Save Article
Like Article
  • Last Updated : 21 Oct, 2021

PHP Constants: PHP Constants are the identifiers that remain the same. Usually, it does not change during the execution of the script. They are case-sensitive. By default, constant identifiers are always uppercase. Usually, a Constant name starts with an underscore or a letter which is followed by a number of letters and numbers. They are no need to write a constant with the $ sign. The constant() function is used to return the value of a constant.

Example:

PHP




<?php
   define("Hello", "Welcome to geeksforgeeks.com!");
   echo Hello;
?>

Output:

Welcome to geeksforgeeks.com!

PHP Variables: A PHP variable is a name given to a memory address that holds data. The basic method to declare a PHP variable is by using a $ sign which is followed by the variable name. A variable helps the PHP code to store information in the middle of the program. If we use a variable before it is assigned then it already has a default value stored in it. Some of the data types that we can use to construct a variable are integers, doubles, and boolean.

 

Example:

PHP




<?php
   $txt = "Hello from geeksforgeeks!";
   $x = 5;
   $y = 10.5;
   echo $txt;
   echo "<br>";
   echo $x;
   echo "<br>";
   echo $y;
?>

Output:

Hello from geeksforgeeks!
5
10.5

Difference between PHP Constants and PHP Variables

PHP ConstantsPHP Variables
In PHP constants there is no need to use $ sign.In PHP Variables the $ sign is been used.

The data type of PHP constant cannot be changed during the

execution of the script.

The data type of the PHP variable can be changed during the

execution of the script.

A PHP constant once defined cannot be redefined.A PHP variable can be undefined as well as can be redefined.

We can not define a constant using any simple assignment operator

rather it can only be defined using define().

We can define a variable using a simple assignment operation(=).
Usually, constants are written in numbers.On the other hand, variables are written in letters and symbols.
PHP constants are automatically global across the entire script.PHP variables are not automatically global in the entire script.
PHP constant is comparatively slower than PHP variableA PHP variable is comparatively faster than the PHP constant

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!