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

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

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

注意: $this 是一个特殊的变量,它不能被赋值。 PHP 7.1.0 之前,间接赋值(例如通过使用可变变量)是可能的。




$Var 'Joe';
"$var$Var";      // 输出 "Bob, Joe"

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


PHP 也提供了另外一种方式给变量赋值:引用赋值。这意味着新的变量简单的引用(换言之,“成为其别名” 或者 “指向”)了原始变量。改动新的变量将影响到原始变量,反之亦然。

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

'Bob';              // 将 'Bob' 赋给 $foo
$bar = &$foo;              // 通过 $bar 引用 $foo
$bar "My name is $bar";  // 修改 $bar 变量
echo $bar;
$foo;                 // $foo 的值也被修改


$bar = &$foo;      // 合法的赋值
$bar = &(24 7);  // 非法; 引用没有名字的表达式

function test()

$bar = &test();    // 非法

虽然在 PHP 中并不需要初始化变量,但对变量进行初始化是个好习惯。未初始化的变量具有其类型的默认值 - 布尔类型的变量默认值是 false,整形和浮点型变量默认值是零,字符串型变量(例如用于 echo 中)默认值是空字符串以及数组变量的默认值是空数组。

示例 #1 未初始化变量的默认值

// 未设置和未引用(不使用上下文)的变量;输出 NULL

// Boolean usage; outputs 'false' (See ternary operators for more on this syntax)
echo($unset_bool "true\n" "false\n");

// String usage; outputs 'string(3) "abc"'
$unset_str .= 'abc';

// Integer usage; outputs 'int(25)'
$unset_int += 25// 0 + 25 => 25

// Float/double usage; outputs 'float(1.25)'
$unset_float += 1.25;

// Array usage; outputs array(1) {  [3]=>  string(3) "def" }
$unset_arr[3] = "def"// array() + array(3 => "def") => array(3 => "def")

// Object usage; creates new stdClass object (see http://www.php.net/manual/en/reserved.classes.php)
// Outputs: object(stdClass)#1 (1) {  ["foo"]=>  string(3) "bar" }
$unset_obj->foo 'bar';

依赖未初始化变量的默认值在某些情况下会有问题,例如把一个文件包含到另一个之中时碰上相同的变量名。 使用未初始化的变量会发出 E_NOTICE 错误,但是在向一个未初始化的数组附加单元时不会。isset() 语言结构可以用来检测一个变量是否已被初始化。

add a note

User Contributed Notes 5 notes

jeff dot phpnet at tanasity dot com
11 years ago
This page should include a note on variable lifecycle:

Before a variable is used, it has no existence. It is unset. It is possible to check if a variable doesn't exist by using isset(). This returns true provided the variable exists and isn't set to null. With the exception of null, the value a variable holds plays no part in determining whether a variable is set.

Setting an existing variable to null is a way of unsetting a variable. Another way is variables may be destroyed by using the unset() construct.

print isset($a); // $a is not set. Prints false. (Or more accurately prints ''.)
$b = 0; // isset($b) returns true (or more accurately '1')
$c = array(); // isset($c) returns true
$b = null; // Now isset($b) returns false;
unset($c); // Now isset($c) returns false;

is_null() is an equivalent test to checking that isset() is false.

The first time that a variable is used in a scope, it's automatically created. After this isset is true. At the point at which it is created it also receives a type according to the context.

= true;   // a boolean
$a_str = 'foo';    // a string

If it is used without having been given a value then it is uninitalized and it receives the default value for the type. The default values are the _empty_ values. E.g  Booleans default to FALSE, integers and floats default to zero, strings to the empty string '', arrays to the empty array.

A variable can be tested for emptiness using empty();

= 0; //This isset, but is empty

Unset variables are also empty.

empty($vessel); // returns true. Also $vessel is unset.

Everything above applies to array elements too.

= array();
//Now isset($item) returns true. But isset($item['unicorn']) is false.
//empty($item) is true, and so is empty($item['unicorn']

$item['unicorn'] = '';
//Now isset($item['unicorn']) is true. And empty($item) is false.
//But empty($item['unicorn']) is still true;

$item['unicorn'] = 'Pink unicorn';
//isset($item['unicorn']) is still true. And empty($item) is still false.
//But now empty($item['unicorn']) is false;

For arrays, this is important because accessing a non-existent array item can trigger errors; you may want to test arrays and array items for existence with isset before using them.
anisgazig at gmail dot com
1 year ago
clear concept of variable declaration rules and classification

variable declaration rules:

1.start with dollar sign($)
2.first letter of variable name comes from a-zA-z_
3.next letters of variable name comes from a-zA-Z0-9_
4.no space,no syntex

classification of variables:

Variable are mainly Two types
1.Predefined Variable
2.User Define Variable

Predefined Variable
There are 12 predefined variables in php 8

User Define Variable
User Define variable are 3 types
1.variable scope
2.variable variables
3.reference variable

Variable Scope
variable scope are 3 types
1.local scope
2.global scope
3.static variable
anisgazig at gmail dot com
9 months ago
$this is a special variable so we can not assign it. But before PHP 7.1.0, indirect assignments such as variable variables are allowed.

$bd = "this";
$$bd = "CountryNickName";

echo $this;//allowed prior to PHP 7.1.0

but from the version of 7.1.0, it was not allowed and throw a fatal error
anisgazig at gmail dot com
1 year ago
$this is a special variable so we can not assign it.But Prior to PHP 7.1.0, indirect assignment such as variable variables are allowed.

$bd = "this";
$$bd = "CountryNickName";

echo $this;//allowed prior to PHP 7.1.0

but from the version of 7.1.0,it was allowed.
5 years ago
I highly recommend to use an editor that can list all variable names in a separate window.

The reason are typing errors in variable names.

= "nobody";
// Now we want to use $somename  somewhere
echo $somemane ;
And wonder why it doesn't print "nobody".
The reason is simple, we have a typing error in $somename and $somemane is a new variable.

In this example it might be easy to find. But if you use variables to calculate some things, you might hardly find it and ask yourself why your calculation is always wrong.
With an editor that list all variable names in a separate window such "double" variables but with wrong typing can be easily found.

It would have been better, if the PHP language would require to use some sort of keyword to define a variable the first time.
To Top