|
|
 |
Chapter 12. Variables
Variables in PHP are represented by a dollar sign followed by the
name of the variable. The variable name is case-sensitive.
Variable names follow the same rules as other labels in PHP. A
valid variable name starts with a letter or underscore, followed
by any number of letters, numbers, or underscores. As a regular
expression, it would be expressed thus:
'[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'
Note:
For our purposes here, a letter is a-z, A-Z, and the ASCII
characters from 127 through 255 (0x7f-0xff).
For information on variable related functions, see the
Variable Functions Reference.
In PHP 3, variables are always assigned by value. That is to say,
when you assign an expression to a variable, the entire value of
the original expression is copied into the destination
variable. This means, for instance, that after assigning one
variable's value to another, changing one of those variables will
have no effect on the other. For more information on this kind of
assignment, see the chapter on Expressions.
As of PHP 4, PHP offers another way to assign values to variables:
assign by reference.
This means that the new variable simply references (in other words,
"becomes an alias for" or "points to") the original variable.
Changes to the new variable affect the original, and vice versa.
This also means that no copying is performed; thus, the assignment
happens more quickly. However, any speedup will likely be noticed
only in tight loops or when assigning large
arrays or
objects.
To assign by reference, simply prepend an ampersand (&) to the
beginning of the variable which is being assigned (the source
variable). For instance, the following code snippet outputs 'My
name is Bob' twice:
One important thing to note is that only named variables may be
assigned by reference.
User Contributed Notes
Variables
josh at PraxisStudios dot com
17-May-2005 03:06
As with echo, you can define a variable like this:
<?php
$text = <<<END
<table>
<tr>
<td>
$outputdata
</td>
</tr>
</table>
END;
?>
The closing END; must be on a line by itself (no whitespace).
user at host dot network
01-May-2005 07:17
pay attention using spaces, dots and parenthesis in case kinda like..
$var=($number>0)?1.'parse error':0.'here too';
the correct form is..
$var=($number>0)?1 .'parse error':0 .'here too';
or
$var=($number>0)?(1).'parse error':(0).'here too';
or
$var = ($number > 0) ? 1 . 'parse error' : 0 . 'here too';
etc..
i think that's why the parser read 1. and 0. like decimal numbers not correctly written, point of fact
$var=$number>0?1.0.'parse error':0.0.'here too';
seems to work correctly..
david at rayninfo dot co dot uk
25-Apr-2005 06:01
When constructing strings from text and variables you can use curly braces to "demarcate" variables from any surrounding text where, for whatever reason, you cannot use a space eg:
$str="Hi my name is ${bold}$name bla-bla";
which AFAIK is the same as
$str="Hi my name is {$bold}$name bla-bla";
zzapper
mike at go dot online dot pt
07-Apr-2005 11:18
In addition to what jospape at hotmail dot com and ringo78 at xs4all dot nl wrote, here's the sintax for arrays:
<?php
$foo1 = array ("a", "b", "c");
$foo2 = array ("d", "e", "f");
$num = 1;
$cell = 2;
echo ${foo.$num}[$cell]; $num = 2;
$cell = 0;
echo ${foo.$num}[$cell]; ?>
lucas dot karisny at linuxmail dot org
14-Feb-2005 06:42
Here's a function to get the name of a given variable. Explanation and examples below.
<?php
function vname(&$var, $scope=false, $prefix='unique', $suffix='value')
{
if($scope) $vals = $scope;
else $vals = $GLOBALS;
$old = $var;
$var = $new = $prefix.rand().$suffix;
$vname = FALSE;
foreach($vals as $key => $val) {
if($val === $new) $vname = $key;
}
$var = $old;
return $vname;
}
?>
Explanation:
The problem with figuring out what value is what key in that variables scope is that several variables might have the same value. To remedy this, the variable is passed by reference and its value is then modified to a random value to make sure there will be a unique match. Then we loop through the scope the variable is contained in and when there is a match of our modified value, we can grab the correct key.
Examples:
1. Use of a variable contained in the global scope (default):
<?php
$my_global_variable = "My global string.";
echo vname($my_global_variable); ?>
2. Use of a local variable:
<?php
function my_local_func()
{
$my_local_variable = "My local string.";
return vname($my_local_variable, get_defined_vars());
}
echo my_local_func(); ?>
3. Use of an object property:
<?php
class myclass
{
public function __constructor()
{
$this->my_object_property = "My object property string.";
}
}
$obj = new myclass;
echo vname($obj->my_object_property, $obj); ?>
jospape at hotmail dot com
05-Feb-2005 01:45
$id = 2;
$cube_2 = "Test";
echo ${cube_.$id};
// will output: Test
ringo78 at xs4all dot nl
14-Jan-2005 02:27
<?
$filename0="k";
$filename1="kl";
$filename2="klm";
$i=0;
for ($varname = sprintf("filename%d",$i); isset ( ${$varname} ) ; $varname = sprintf("filename%d", $i) ) {
echo "${$varname} <br>";
$varname = sprintf("filename%d",$i);
$i++;
}
?>
Carel Solomon
07-Jan-2005 05:02
You can also construct a variable name by concatenating two different variables, such as:
<?
$arg = "foo";
$val = "bar";
${$arg . $val} = "working";
echo $foobar; echo ${$arg . $val}; ?>
Carel
raja shahed at christine nothdurfter dot com
25-May-2004 12:58
<?php
error_reporting(E_ALL);
$name = "Christine_Nothdurfter";
$$name = "'s students of Tyrolean language ";
print " $name{$$name}<br>";
print "$name$Christine_Nothdurfter";
?>
webmaster at surrealwebs dot com
09-Mar-2004 02:31
OK how about a practicle use for this:
You have a session variable such as:
$_SESSION["foo"] = "bar"
and you want to reference it to change it alot throughout the program instaed of typing the whole thing over and over just type this:
$sess =& $_SESSION
$sess['foo'] = bar;
echo $sess['foo'] // returns bar
echo $_SESSION["foo"] // also returns bar
just saves alot of time in the long run
also try $get = $HTTP_GET_VARS
or $post = $HTTP_POST_VARS
webmaster at daersys dot net
20-Jan-2004 10:15
In reference to "remco at clickbizz dot nl"'s note I would like to add that you don't necessarily have to escape the dollar-sign before a variable if you want to output it's name.
You can use single quotes instead of double quotes, too.
For instance:
<?php
$var = "test";
echo "$var"; echo "\$var"; echo '$var'; ?>
Why?
Well, the reason for this is that the PHP Parser will not attempt to parse strings encapsulated in single quotes (as opposed to strings within double quotes) and therefore outputs exactly what it's being fed with :)
To output the value of a variable within a single-quote-encapsulated string you'll have to use something along the lines of the following code:
<?php
$var = 'test';
echo '$var = "' . $var . '"';
?>
HTH
- Daerion
unleaded at nospam dot unleadedonline dot net
14-Jan-2003 08:37
References are great if you want to point to a variable which you don't quite know the value yet ;)
eg:
$error_msg = &$messages['login_error']; // Create a reference
$messages['login_error'] = 'test'; // Then later on set the referenced value
echo $error_msg; // echo the 'referenced value'
The output will be:
test
| |