This chapter will explain PHP variables in details.
What is variable?
As its name suggests variable is a thing which can vary. In programming terms, the PHP variable is a container which can store data. And we can vary its data at any time we need. It’s basically a memory location having a specific memory address and having data type to store data of specific type. Let’s see in details about PHP variables as below. We will also see what are different PHP variables type in details.
Few important features of PHP variables are as follows:
- Every variable name must be unique.
- In PHP all the variables names should have a dollar sign before them.
Example: $name - A variable name must have at least one character.
- Spaces are not allowed in a variable.
- Special characters other than $(dollar) and _ (underscore) are not allowed.
- Every first character after dollar sign can be a letter or underscore.
Example: $first_name;
Now lets see different variable types in PHP.
There are 8 basic variable types in PHP
1 | Integers | are the whole number which doesn’t have decimal point. Ex: 22354. |
2 | Doubles | are floating point numbers having decimal point. Ex: 232.45 |
3 | Booleans | Boolean variable can store only true or false values. |
4 | NULL | Null is special data type which can store only NULL value. |
5 | String | It is a sequence of characters stored in string type variable. |
6 | Arrays | are the collection of values which are having integer index and names in place of an index. |
7 | Objects | variables are used to store instances of classes. |
8 | Resources | are special kind of variable that stores reference to the resources external to PHP. |
In PHP we don’t need to write data type before the variable name, as like another language. Whatever type of data you assign to the variable that variable automatically gets converted into that data type of variable. That’s why PHP is called loosely typed language.
Examples:
1 | $roll = 123 | Integer data type variable |
2 | $cost = 100.45 | Double data type variable |
3 | $flag = true; | Boolean data type variable |
4 | $age = NULL; | Null Data type variable |
5 | $name = “saurabh”; | String data type variable |
6 | $fruits = array(‘orange’,’apple’,’grapes’); | Array data type variable |
7 | $obj_stu = new Student(); | Object variable data type |
8 | $con = mysql_connect(‘localhost’,’root’,’123′); | Resource data type variable |
Variable Scope:
The Scope of a variable can be defined as its range up to which, a variable is available within a program.
There are four types of variable scopes.
- Local variable
- Function parameter
- Global variable
- Static variable
We will see about them in upcoming chapters.