Constants in Php are similar to variables in Php. The only difference between Variables and Constants is Constants are fixed, the value of Constants cannot be change, once something is assigned to it. It will be same forever. In this tutorial, you will learn how to define Constants in Php.
Constants are very helpful for storing data that does not change throughout the program. Common example of such data include saving banking details, user details like email address, password, etc.
How to define constants in Php
Constants in Php defined using the pre define function
define(), which take two arguments: first the name of the constant and followed by value. Once defined the constant value can be accessed at any time just by referring to its name. Here is a simple example:
<?php //Defining constants define("username", "deepsane"); // using constant in a string with echo statement echo "My username is: " . username; // The output will be: My username is deepsane ?>
echo statement in Php is used to output or display the data on web browser. You can learn more about Php echo statement here.
Note: Make sure whenever you define a constant in Php, the value of it won’t change accidentally, while running the program. Otherwise it will through an error.
Naming rules for constants in Php
The naming rules of constants in Php are similar to variable naming rules. There is only exception for constants is it doesn’t required
$ sign to create. Following are the naming rules of constants in Php:
- All constant does not required to start with a
$sign like in variables.
- A constant name cannot start with number or any sign except
- A constant name must start with a character or
- A constant name in PHP can only contain alpha-numeric characters and underscores (
- A constant name cannot contain space anywhere.
- A constant name in Php is case-sensitive. For example: constant names
$golfare two different constants.