![]() |
WebCheatSheet.com |
![]() |
PHP: Variables |
A variable is a holder for a type of data. So, based on its type, a variable can hold numbers, strings, booleans, objects, resources or it can be NULL. In PHP all the variables begin with a dollar sign "$" and the value can be assignes using the "=" operator. The dollar sign is not technically part of the variable name, but it is required as the first character for the PHP parser to recognize the variable as such. Another important thing in PHP is that all the statements must end with a semicolon ";". In PHP we needn't have to specify the variable type, as it takes the data type of the assigned value. The contents of a variable can be changed at any time, and so can its type. To declare a variable, you must include it in your script. You can declare a variable and assign it a value in the same statement. Here is some code creating and assigning values to a couple of variables:
The output is: Have a nice day! My favourite number is 5. Case Sensitivity One thing that causes many problems and take hours of finding mistakes is case sensitivity. PHP is case sensitive. Have a look at the following code:
PHP Variable Naming Conventions There are a few rules that you need to follow when choosing a name for your PHP variables.
One important thing to note if you are coming from another programming language there is no size limit for variables. Variable References PHP also allows you to do some neat things with variables. It allows you to create aliases for variables, and it also allows you to have variables whose name is a variable. A variable reference, or alias, is a variable assigned to refer to the same information as another variable. To assign an alias to a variable, you use the reference operator, which is an equals sign followed by an ampersand. The following code snippet outputs 'Have a nice day!' twice:
Environment Variables Beyond the variables you declare in your code, PHP has a collection of environment variables, which are system defined variables that are accessible from anywhere inside the PHP code. All of these environment variables are stored by PHP as arrays. Some you can address directly by using the name of the index position as a variable name. Other can only be accessed through their arrays. Some of the environment variables include:
The code to use the environment variables will be as follows:
|
![]() |
![]() |
Copyright © 2005-2007 www.WebCheatSheet.com All Rights Reserved. |