PHP Variables and Constants

Variables are used for storing values that can change over the course of a script, whereas the constants are used for storing fixed values that doesn't change.

What is Variables in PHP

Variables are used to store data, like text strings, numbers or arrays.

Important things to know about variables in PHP:

  • In PHP, a variable does not need to be declared before adding a value to it. PHP automatically converts the variable to the correct data type, depending on its value.
  • After declaring a variable it can be reused throughout the code.
  • The assignment operator (=) used to assign value to a variable.

In PHP variable can be declared as: $var_name = value;

  • <?php
  • $txt = "Hello World!";
  • $number = 10;
  • ?>

In the above example we have created two variables where first one has assigned with a string value and the second has assigned with a number.

Naming Conventions for PHP Variables

These are the following rules for naming a PHP variable:

  • All variables in PHP start with a dollar sign ($), followed by the name of the variable.
  • A variable name must start with a letter or the underscore character (_).
  • A variable name cannot start with a number.
  • A variable name in PHP can only contain alpha-numeric characters and underscores (A-z, 0-9, and _).
  • A variable name cannot contain spaces.
 

Note:Variable names in PHP are case sensitive, it means $x and $X are two different variables. So be careful while defining variable names.


What is Constants in PHP

A constant is an identifier (name) for a simple value. A constant value cannot change during the execution of the script (except for magic constants). Constants are useful for storing data that doesn't change while the script is running. Common examples of such data include configuration settings (such as database usernames and passwords).

Constants are defined using define() function, which accepts two arguments: the name of the constant, and its value. Here is an example of defining and using a constant in a script:

  • <?php
  • // Defining constants
  • define("PROGRAM", "PHP");
  • define("VERSION", "5.5.14");
  •  
  • // Using constants
  • echo 'Current ' . PROGRAM . ' version is: ' . VERSION;
  • ?>

The output of the above code will be:

Current PHP version is: 5.5.14

Naming Conventions for PHP Constants

Name of constants must follow the same rules as variable names, which means a valid constant name must starts with a letter or underscore, followed by any number of letters, numbers, or underscores, with one exception: the $ prefix is not required for constant names.

 

Note:By convention, constant names are usually entirely uppercased. This is for their easy identification and differentiation from "regular" variables in a script.

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.