Friday, 6 July 2018

PHP variables and constants


In this tutorial we will learn about PHP variables and constants.

What is a variable?

A variable is simply a box or a container that holds certain value and this value can change.

PHP Variable

All PHP variables starts with a $ sign. So, for example if we want to create a variable to store name then we can write.
$name = "Yusuf Shakeel";
Also note, we end a statement using a semicolon ;

Variable name rules

Following are the rules that must be followed when creating a variable in PHP.
  • Every variable name must begin with a $ sign.
  • The first character after the dollar sign must be either a letter or underscore sign.
  • Remaining characters of the variable name can be letters, numbers or underscore sign.
Following are valid variable names.
$name = "Yusuf Shakeel";
$country_name = "India";
$points = 10;
$_flag = 0;
And following are invalid variable names.
$123 = "Some value";
//first character after $ can't be digit.

$country-name = "Some value";
//- character not allowed

What is a constant?

A constant is also like a container that holds some value but this value can't be changed.

PHP Constant

Value of a PHP constant remains fixed during the execution of the code.
Name of a PHP constant do not start with a $ sign while rest of the other rules of naming remains the same.

Constant name rules

Following are the rules that must be followed when creating a constant in PHP.
  • Constant name must not begin with a $ sign.
  • The first character must be either a letter or underscore sign.
  • Remaining characters of the variable name can be letters, numbers or underscore sign.
Note! We generally use capital letters to name a constant.
To define a constant we use the define() function. This function takes two parameters. First one is for the name of the constant and the second is for the value of the constant.
Following are valid constant names.
define('ERROR_CODE_FILE_NOT_FOUND', 404);
define('HAPPY_CODE', 123);

0 comments:

Post a Comment