©
Ce document utilise Manuel du site Web PHP chinois Libérer
PHP 中的变量用一个美元符号后面跟变量名来表示。变量名是区分大小写的。
变量名与 PHP 中其它的标签一样遵循相同的规则。一个有效的变量名由字母或者下划线开头,后面跟上任意数量的字母,数字,或者下划线。按照正常的正则表达式,它将被表述为:'[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'。
Note: 在此所说的字母是 a-z,A-Z,以及 ASCII 字符从 127 到 255(0x7f-0xff)。
Note: $this 是一个特殊的变量,它不能被赋值。
请参见用户空间命名指南。
有关变量的函数信息见变量函数。
<?php
$var = 'Bob' ;
$Var = 'Joe' ;
echo " $var , $Var " ; // 输出 "Bob, Joe"
$ 4site = 'not yet' ; // 非法变量名;以数字开头
$_4site = 'not yet' ; // 合法变量名;以下划线开头
$i站点is = 'mansikka' ; // 合法变量名;可以用中文
?>
变量默认总是传值赋值。那也就是说,当将一个表达式的值赋予一个变量时,整个原始表达式的值被赋值到目标变量。这意味着,例如,当一个变量的值赋予另外一个变量时,改变其中一个变量的值,将不会影响到另外一个变量。有关这种类型的赋值操作,请参阅表达式一章。
PHP 也提供了另外一种方式给变量赋值:引用赋值。这意味着新的变量简单的引用(换言之,“成为其别名” 或者 “指向”)了原始变量。改动新的变量将影响到原始变量,反之亦然。
使用引用赋值,简单地将一个 & 符号加到将要赋值的变量前(源变量)。例如,下列代码片断将输出“My name is Bob”两次:
<?php
$foo = 'Bob' ; // 将 'Bob' 赋给 $foo
$bar = & $foo ; // 通过 $bar 引用 $foo
$bar = "My name is $bar " ; // 修改 $bar 变量
echo $bar ;
echo $foo ; // $foo 的值也被修改
?>
有一点重要事项必须指出,那就是只有有名字的变量才可以引用赋值。
<?php
$foo = 25 ;
$bar = & $foo ; // 合法的赋值
$bar = &( 24 * 7 ); // 非法; 引用没有名字的表达式
function test ()
{
return 25 ;
}
$bar = & test (); // 非法
?>
虽然在 PHP 中并不需要初始化变量,但对变量进行初始化是个好习惯。未初始化的变量具有其类型的默认值 - 布尔类型的变量默认值是
FALSE
,整形和浮点型变量默认值是零,字符串型变量(例如用于 echo
中)默认值是空字符串以及数组变量的默认值是空数组。
Example #1 未初始化变量的默认值
<?php
// Unset AND unreferenced (no use context) variable; outputs NULL
var_dump ( $unset_var );
// 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' ;
var_dump ( $unset_str );
// Integer usage; outputs 'int(25)'
$unset_int += 25 ; // 0 + 25 => 25
var_dump ( $unset_int );
// Float/double usage; outputs 'float(1.25)'
$unset_float += 1.25 ;
var_dump ( $unset_float );
// Array usage; outputs array(1) { [3]=> string(3) "def" }
$unset_arr [ 3 ] = "def" ; // array() + array(3 => "def") => array(3 => "def")
var_dump ( $unset_arr );
// 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' ;
var_dump ( $unset_obj );
?>
依赖未初始化变量的默认值在某些情况下会有问题,例如把一个文件包含到另一个之中时碰上相同的变量名。另外把 register_globals 打开是一个主要的安全隐患。使用未初始化的变量会发出 E_NOTICE 错误,但是在向一个未初始化的数组附加单元时不会。 isset() 语言结构可以用来检测一个变量是否已被初始化。
[#1] Kubo2 [2015-03-22 12:05:41]
What's funny with PHP's $this variable and variable variables:
Imagine you have a class like below:
<?php
class Bar {
private $foo = 9;
function __construct() {
$varName = 'this';
$$varName = 'text'; // sets $this to 'text'
// outputs 'text'
echo $this;
// instead of Notice: Trying to get property of non-object, outputs 9
echo $this->foo;
}
}
$a = new Bar;
var_dump($a); // object(Bar)#1 (1) {...}
?>
So PHP doesn't rely on $this's value itself, but rather on its name and the syntax you're accessing instance's properties and calling its methods. Also it doesn't pass any hidden parameter $this to the instance's methods nor it automatically returns $this from the __construct()or, like often being described in books which tries to teach OOP.
$this is simply an undefined variable with special meaning of its name.
[#2] karst at onlinq dot nl [2014-11-17 11:34:02]
From the "Properties" page, about initialising properties:
"This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated. "
So if you define a variable in a class (as a member variable/property), things like public <?php $test = 2+3; ?> are invalid, because logic has to be performed on the right hand side.
It HAS to be either a constant, or a scalar value (int/string/bool/float). Not even another variable which is a constant (so <?php public $test = "test"; public $invalid = $test; ?> would not work.
Just thought this should be mentioned here for all those like me who get here before getting to the "Properties" page.
[#3] jeff12 at fastpitchcentral dot com [2014-03-20 19:38:01]
While the recommendation here is to initialize variables, there is a very good reason to definitely initialize variables.
I just had the unpleasant task of making numerous folks happy that the Apache "error_log" is now much smaller. We had over 1500 variables that showed up as "error" in the error_log file. In many cases just one uninitialized variable might cause 10s or 100s of thousands of records to be entered in the "error_log".
While it may not be necessary to initialize variables, there can be a significant cost if you do not do so.
And no, that website was not willing to lower the bar and not write to the "error_log" file if it was simply a case of uninitialized variables. It was also the case that in a small percentage of cases the variables newly initialized caused me to scratch my head and conclude that a blank or zero might cause different logic to occur.
[#4] tymac at hotmail dot com [2013-09-19 04:05:31]
Hi,
something like $foo = &myfunc(); seems to work fine.
Regards.
[#5] php at richardneill dot org [2013-08-26 01:05:49]
Note that "$1" is not a variable name. PHP treats it literally, even when it is in double quotes. Eg:
$fruit="apple";
echo "This $fruit costs $1 ";
This is especially notable when using $1, $2 etc inside parameterised queries in SQL.
[#6] megan at voices dot com [2012-01-05 08:44:42]
"Note: $this is a special variable that can't be assigned."
While the PHP runtime generates an error if you directly assign $this in code, it doesn't for $$name when name is 'this'.
<?php
$this = 'text'; // error
$name = 'this';
$$name = 'text'; // sets $this to 'text'
?>
[#7] maurizio dot domba at pu dot t-com dot hr [2011-01-21 02:23:57]
If you need to check user entered value for a proper PHP variable naming convention you need to add ^ to the above regular expression so that the regular expression should be '^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'.
Example
<?php
$name="20011aa";
if(!preg_match('/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/',$name))
echo $name.' is not a valid PHP variable name';
else
echo $name.' is valid PHP variable name';
?>
Outputs: 2011aa is valid PHP variable name
but
<?php
$name="20011aa";
if(!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/',$name))
echo $name.' is not a valid PHP variable name';
else
echo $name.' is valid PHP variable name';
?>
Outputs: 2011aa is not a valid PHP variable name
[#8] jeff dot phpnet at tanasity dot com [2010-09-11 16:11:10]
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.
<?php
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.
<?php
$a_bool = 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();
<?php
$a = 0; //This isset, but is empty
?>
Unset variables are also empty.
<?php
empty($vessel); // returns true. Also $vessel is unset.
?>
Everything above applies to array elements too.
<?php
$item = 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.
[#9] Edoxile [2010-03-06 13:25:25]
When wanting to switch two variables from content, you can use the XOR operator:
<?PHP
$a=5;
$b=3;
//Please mind the order of these, as it's important for the outcome.
$a^=$b;
$b^=$a;
$a^=$b;
echo $a.PHP_EOL.$b;
?>
This will also work on strings, but it won't work on arrays and objects, so for them you'll have to use the serialize() function before the operation, and the unserialize() function after.