基礎

PHP 中的變數用一個錢字元號後面跟變數名來表示。變數名是區分大小寫的。

變數名與 PHP 中其它的標籤一樣遵循相同的規則。一個有效的變數名由字母或者下劃線開頭,後面跟上任意數量的字母,數字,或者下劃線。按照正常的正則表示式,它將被表述為:'[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'。

Note: 在此所說的字母是 a-z,A-Z,以及 ASCII 字元從 127 到 255(0x7f-0xff)。

Tip

可以參考Userland Naming Guide

有關變數的函式資訊見變數函式

<?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.
?>

雖然在 PHP 中並不需要初始化變數,但這是個好習慣。未初始化的變數具有其類型的默認值 - FALSE,零,空字元串或者空數組。

Example #1 未初始化變數的默認值

<?php
echo ($unset_bool "true" "false"); // false
$unset_int += 25// 0 + 25 => 25
echo $unset_string "abc"// "" . "abc" => "abc"
$unset_array[3] = "def"// array() + array(3 => "def") => array(3 => "def")
?>

依賴未初始化變數的默認值在某些情況下會有問題,例如把一個文件包含到另一個之中時碰上相同的變數名。另外把 register_globals 打開是一個主要的安全隱患E_NOTICE 級別的錯誤會在碰上未初始化的變數時發出,但是在向一個未初始化的數組附加單元時不會。isset() 語言結構可以用來檢測一個變數是否已被初始化。

add a note add a note

User Contributed Notes 6 notes

up
66
jeff dot phpnet at tanasity dot com
13 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.

<?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.
up
4
anisgazig at gmail dot com
3 years 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
1.$GLOBALS
2.$_SERVER
3.$_REQUEST
4.$_FILES
5.$_ENV
6.$_SESSION
7.$_COOKIE
8.$_GET
9.$_POST
10.$http_response_header
11.$argc
12.$argv

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
up
-10
Anonymous
7 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.

<?php
$somename
= "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.

BTW:
It would have been better, if the PHP language would require to use some sort of keyword to define a variable the first time.
up
-24
baoquyen804 at gmail dot com
6 years ago
When examining the variable name with the regular expression [a-zA-Z_ \ x7f- \ xff] [a-zA-Z0-9_ \ x7f- \ xff] this will cause an error:

<?php
$name
="aa'1'";
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';
// output aa'1' is valid PHP variable name
//but:
$aa'1' = 10; // error syntac
?>

instead use it ^[a-zA-Z][_]?[\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

<?php
$name
="aa'1'";
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';
// output aa'1' is not valid PHP variable name
?>
up
-31
maurizio dot domba at pu dot t-com dot hr
13 years ago
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
up
-7
anisgazig at gmail dot com
3 years 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.
To Top