Difference between Constant and Variable in PHP
Constant in PHP
A constant in PHP is a value that cannot be changed once it is declared. It is defined using the ‘define()‘ function and their names are case sensitive.
Example:
<?php
define("Hello", "Welcome to Webeduclick!");
echo Hello;
?>
Output:
Welcome to Webeduclick!
Variable in PHP
A variable in PHP is a placeholder for storing data that can be changed during the execution of a script. Variables are defined using a dollar sign ($) followed by the variable name. It can store different types of data such as strings, integers, floats, arrays, objects, etc.
<?php $a=5; $b=10; $c=$a+$b; echo "$c"; ?>
Output:
15
Difference between Constant and Variable
| Constant | Variable |
|---|---|
| 1. In PHP constants, there is no need to use $ sign. | 1. In PHP Variables, the $ sign is been used. |
| 2. A PHP constant once defined cannot be redefined. | 2. A PHP variable can be undefined as well as can be redefined. |
| 3. The data type of PHP constant cannot be changed during the execution of the script. | 3. The data type of the PHP variable can be changed during the execution of the script. |
| 4. PHP constants are written in numbers. | 4. PHP variables are written in letters and symbols. |
| 5. PHP constant is comparatively slower than PHP variable | 5. A PHP variable is comparatively faster than the PHP constant |