Learning Resources
 

Variable and constants


In programming, a variable means a value holder. A variable can hold the same value or the value it holds can get changed during the runtime of a program.

01. 02.
03.$greeting = 'Welcome';
04.
05.$name = 'Ram';
06.echo "$greeting $name";
07.echo '
';
08.
09.$name = 'Ramu';
10.echo "$greeting $name";
11.echo '
';
12.
13.$name = 'Raj';
14.echo "$greeting $name";
15.echo '
';
16.
17.?>

Run above script in web browser and you would see following three lines.

Welcome Ram
Welcome Ramu
Welcome Raj

In this script both $greeting and $name are variables. You can see that $greeting holds the same value throughout the script while value of $name gets changed. We print
tags just to have line breaks in the browser.

Naming Variables
In PHP, all variables should start with $ sign. The part after $ sign is called variable name.

  •     Variable names can only contain letters, numbers and underscores.
  •     A variable name should only start with a letter or an underscore.
  •     Variable names are case-sensitive. That means $Greeting and $greeting are two different variables.

Some good practices in variable naming.
1.$firstName // Correct
2.$first_name // Correct
3.$firstName1 // Correct
4.$_firstName // Correct
5.$first-name // Wrong (Hyphen is not allowed)
6.$4firstName // Wrong (Starts with a number)

Arrays
All the variables considered so far could contain only one value at a time. Arrays provide a way to store a set of values under one variable.

Predefined Variables
PHP provides a set of predefined variables. Most of them are arrays. Their availability and values are based on the context. For an example $_POST contains all the values submitted via a web form that used post method. Refer PHP manual for more information on predefined variables.

Constants
As name describes, constants hold values that don’t get changed during the runtime of a script. Same naming rules apply for constants except that $ sign is not used when defining constants. To give an emphasis to constants, it’s a common practice to define constant names in upper-case.
1.define('SITE_URL', 'https://www.example.com');
2.echo SITE_URL; // Would print https://www.example.com

Once defined, a new value cannot be assigned to a constant.
1.define('SITE_URL', 'https://www.google.com');
2.echo SITE_URL; // Would still print https://www.example.com

 

It includes the following topics -