章 12. 变量

基础

PHP 中的变量用一个美元符号后面跟变量名来表示。变量名是区分大小写的。

变量名与 PHP 中其它的标签一样遵循相同的规则。一个有效的变量名由字母或者下划线开头,后面跟上任意数量的字母,数字,或者下划线。按照正常的正则表达式,它将被表述为:'[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'。

注: 在此所说的字母是 a-z,A-Z,以及 ASCII 字符从 127 到 255(0x7f-0xff)。

有关变量的函数信息见变量函数

<?php
$var
= 'Bob';
$Var = 'Joe';
echo
"$var, $Var";      // 输出 "Bob, Joe"

$4site = 'not yet';     // 非法变更名;以数字开头
$_4site = 'not yet';    // 合法变量名;以下划线开头
$i站点is = 'mansikka';  // 合法变量名;可以用中文
?>

PHP 3 中,变量总是传值赋值。那也就是说,当将一个表达式的值赋予一个变量时,整个原始表达式的值被赋值到目标变量。这意味着,例如,当一个变量的值赋予另外一个变量时,改变其中一个变量的值,将不会影响到另外一个变量。有关这种类型的赋值操作,请参阅表达式一章。

PHP 4 提供了另外一种方式给变量赋值:引用赋值。这意味着新的变量简单的引用(换言之,“成为其别名” 或者 “指向”)了原始变量。改动新的变量将影响到原始变量,反之亦然。这同样意味着其中没有执行复制操作;因而,这种赋值操作更加快速。不过只有在密集的循环中或者对很大的数组对象赋值时才有可能注意到速度的提升。

使用引用赋值,简单地将一个 & 符号加到将要赋值的变量前(源变量)。例如,下列代码片断将输出“My name is Bob”两次:

<?php
$foo
= 'Bob';              // Assign the value 'Bob' to $foo
$bar = &$foo;              // Reference $foo via $bar.
$bar = "My name is $bar";  // Alter $bar...
echo $bar;
echo
$foo;                 // $foo is altered too.
?>

有一点重要事项必须指出,那就是只有有名字的变量才可以引用赋值。

<?php
$foo
= 25;
$bar = &$foo;      // This is a valid assignment.
$bar = &(24 * 7);  // Invalid; references an unnamed expression.

function test()
{
   return
25;
}

$bar = &test();    // Invalid.
?>


add a note add a note User Contributed Notes
molnaromatic at gmail dot com
20-May-2006 08:44
Simple sample and variables and html "templates":
The PHP code:
variables.php:
<?php
$SYSN
["title"] = "This is Magic!";
$SYSN["HEADLINE"] = "Ez magyarul van"; // This is hungarian
$SYSN["FEAR"] = "Bell in my heart";
?>

index.php:
<?php
include("variables.php");
include(
"template.html");
?>

The template:
template.html

<html>
<head><title><?=$SYSN["title"]?></title></head>
<body>
<H1><?=$SYSN["HEADLINE"]?></H1>
<p><?=$SYSN["FEAR"]?></p>
</body>
</html>
This is simple, quick and very flexibile
warhog at warhog dot net
28-Dec-2005 03:11
> 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]*'

..is not quite true. You can, in fact, only declare variables having a name like this if you use the syntax <?php $varname = "naks naks"; ?>.. but in fact a variable can have moreless any name that is a string... e.g. if you look at an array you can have
<?php
$arr
[''];
$arr['8'];
$arr['-my-element-is-so-pretty-useless-'];
?>
.. by accessing the variables-namespace via {} you can have the same functinalities for all variables, e.g.

<?php ${''} = "my empty variable"; ?>

is a valid expression and the variable having the empty string as name will have the value "my empty variable".

read the chapter on "variable variables" for further information.
Mike at ImmortalSoFar dot com
26-Nov-2005 06:03
References and "return" can be flakey:

<?php
//  This only returns a copy, despite the dereferencing in the function definition
function &GetLogin ()
{
   return
$_SESSION['Login'];
}

//  This gives a syntax error
function &GetLogin ()
{
   return &
$_SESSION['Login'];
}

//  This works
function &GetLogin ()
{
  
$ret = &$_SESSION['Login'];
   return
$ret;
}
?>
david at removethisbit dot futuresbright dot com
10-Nov-2005 05:25
When using variable variables this is invalid:

$my_variable_{$type}_name = true;

to get around this do something like:

$n="my_variable_{$type}_name";
${$n} = true;

(or $$n - I tend to use curly brackets out of habit as it helps t reduce bugs ...)
ludvig dot ericson at gmail dot com
13-Oct-2005 07:33
On the previous note:

This is due to how evaluation works. PHP will think of it as:

$a = whatever $b = $c is
$b = whatever $c = 1 is

... because an expression is equal to what it returns.

Therefore $c = 1 returns 1, making $b = $c same as $b = 1, which makes $b 1, which makes $a be $b, which is 1.

$a = ($b = $c = 1) + 2;
Will have $a be 3 while $b and $c is 1.

Hope that clears something up.
Chris Hester
31-Aug-2005 08:09
Variables can also be assigned together.

<?php
$a
= $b = $c = 1;
echo
$a.$b.$c;
?>

This outputs 111.
Mike Fotes
10-Jul-2005 02:46
In conditional assignment of variables, be careful because the strings may take over the value of the variable if you do something like this:

<?php
$condition
= true;

// Outputs " <-- That should say test"
echo "test" . ($condition) ? " <-- That should say test" : "";
?>

You will need to enclose the conditional statement and assignments in parenthesis to have it work correctly:

<?php
$condition
= true;

// Outputs "test <-- That should say test"
echo "test" . (($condition) ? " <-- That should say test " : "");
?>
josh at PraxisStudios dot com
18-May-2005 04: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
02-May-2005 08: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
26-Apr-2005 07: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
08-Apr-2005 12:18
In addition to what jospape at hotmail dot com and ringo78 at xs4all dot nl wrote, here's the sintax for arrays:

<?php
//considering 2 arrays
$foo1 = array ("a", "b", "c");
$foo2 = array ("d", "e", "f");

//and 2 variables that hold integers
$num = 1;
$cell = 2;

echo ${
foo.$num}[$cell]; // outputs "c"

$num = 2;
$cell = 0;

echo ${
foo.$num}[$cell]; // outputs "d"
?>
lucas dot karisny at linuxmail dot org
15-Feb-2005 08: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); // Outputs:  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(); // Outputs: my_local_variable
?>

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); // Outputs: my_object_property
?>
jospape at hotmail dot com
05-Feb-2005 03:45
$id = 2;
$cube_2 = "Test";

echo ${cube_.$id};

// will output: Test
ringo78 at xs4all dot nl
15-Jan-2005 04:27
<?
// I am beginning to like curly braces.
// I hope this helps for you work with them
$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 07:02
You can also construct a variable name by concatenating two different variables, such as:

<?

$arg
= "foo";
$val = "bar";

//${$arg$val} = "in valid";    // Invalid
${$arg . $val} = "working";

echo
$foobar;    // "working";
//echo $arg$val;        // Invalid
//echo ${$arg$val};    // Invalid
echo ${$arg . $val};    // "working"

?>

Carel
raja shahed at christine nothdurfter dot com
26-May-2004 01:58
<?php
error_reporting
(E_ALL);

$name = "Christine_Nothdurfter";
// not Christine Nothdurfter
// you are not allowed to leave a space inside a variable name ;)
$$name = "'s students of Tyrolean language ";

print
" $name{$$name}<br>";
print 
"$name$Christine_Nothdurfter";
// same
?>
webmaster at surrealwebs dot com
10-Mar-2004 04: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
21-Jan-2004 12: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"; // Will output the string "test"

echo "\$var"; // Will output the string "$var"

echo '$var'; // Will do the exact same thing as the previous line
?>

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';
/*
Using single quotes here seeing as I don't need the parser to actually parse the content of this variable but merely treat it as an ordinary string
*/

echo '$var = "' . $var . '"';
/*
Will output:
$var = "test"
*/
?>

HTH
- Daerion
unleaded at nospam dot unleadedonline dot net
15-Jan-2003 10: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