PHP Constants

PHP constants is an identifier (name) for a simple value.
As the name suggests, that value cannot change during the execution of the script.

Rules for constants

  • The rules for naming constant name is same as rules for naming variable names.
  • $ sign is not used with constants.
  • Constants are case-sensitive.
  • A constant name must start with letter(a-z or A-Z) or underscore(_) followed by any number of letters, numbers or underscores.
  • Constant name cannot start with numbers.
  • The scope of constant is global means you can access constants anywhere in script.

 

Syntax to create php constant:

Following is a general syntax to create constant:

define() – It is a function use to define constant.
constant_name – For convention constant_name are always uppercase.
constant_value – must to specifies.
true/false specifies whether the constant name should be case-insensitive.
If you do not mention anything then it is by default false.

Example:

 

Constants are case-sensitive.

Let’s see following two examples to understand,

Output

 

Difference between variables and constants

  • To create variable, you have to use doller($) sign before variable name.
    But there is no need to write a dollar sign ($) before a constant
  • Variables have there scoping rules, local, global, static.
    Constants accessed anywhere in script without regard to scoping rules.
  • You can change value of variable at anywhere in program.
    But Constants can not be redefined.
  • Value of variable is simply assign using assignment operator(=).
    Constants cannot be defined by simple assignment, they defined using the define() function.

Ankit Wasankar

Senior Java Developer
Java 11 | Microservices | Reactjs | SQL

Help others by sharing the content!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.