Everything PHP: Variables
Posted on January 13th, 2009
This week we’ll be going more in-depth about variables, as they are a key part of programming. As we said last week, variables are used to temporarily store data. Let’s look at our example again:
$variable_name = 'Value of variable';
In this example, the variable $variable_name contains the string Value of variable, which need to be enclosed in quotes. Let’s get into some more uses of variables, and related information about them.
Variables within Variables
It is possible to specify a variable inside of a variable, like so:
$a = 'First variable.'; $b = $a;
You might do this if you need to modify the value of $a, while still keeping the original value intact.
Joining Strings with Variables and Variables with Variables
You may want to add more than one string or variables (or those interweaved) into a single variable. This is achieved like this:
$c = 26; $d = 'Number of penguins on the roof: ' . $c; $e = 'Blah'; $f = $e . $c;
This is done by joining them with a period. It is also possible to later on add to a variable, which is done like so:
$g = 'The proximity of the meteor is'; // Later in the file... $g .= 230505 . 'kilometers';
You simply use the same variable name as the variable you want to add to, and then add a period before the equals sign (for appending) or after the equals sign (for prepending).
Referencing a Variable
Remember how one of the uses of using a variable within a variable was to leave the original untouched? Well, there may be times when you want changes to a variable to affect its source variable too (and vice-versa). This is called assigning by reference. This basically makes the new variable an alias for the old one.
$h = 'Hello world!'; $i = &$h;
Assigning a variable by reference is done by prepending an ampersand to the original variable.
Math
Yes, you can even do Math calculations within variables.
$j = 4 + 10; $k = 3 + (5 * 3) / 3;
You can also increment or decrease by 1 simply like this:
$l = 5++; $m = 2--;
Single- or Double-Quotes
Whenever you use a string in a variable, it must be enclosed in quotes. As for which quotes to use (single or double), that depends on a few things. If you want to use variables within a string or line breaks (\n), you must use double quotes. However, if your string is just a plain string, you can safely use single quotes.
Reserved Variables
There are a few variable names that you cannot use, as they’re predefined or reserved within PHP. A list of the “off-limit” variable names is available here ($this is also reserved).
Posted in Development | 334 views | | Digg This | del.icio.us | Technorati
Related Topics:
Everything PHP: Constants and Globals
PHP Tutorial – Part 2 of 5
Everything PHP: Syntax
Everything PHP: Functions
WordPress Development: The WPDB Class
Comments
Sorry, the comment form is closed at this time.
No comments yet.