PHP 变量

声明、作用域、可变变量、引用赋值、以及变量检测函数。

Beginner
Key PointsPHP 变量无需声明,赋值即创建;函数内的变量和外部互不相通。

基本用法

PHP
<?php
$name = "张三";
$age = 28;
$price = 99.5;
$active = true;
$nothing = null;

echo "$name $age $price\n";
var_dump($active, $nothing);

// 变量可以随时改变类型(弱类型)
$x = 1;
$x = "现在是字符串";
$x = [1, 2];
var_dump($x);
Output
张三 28 99.5
bool(true)
NULL
array(2) {
  [0]=>
  int(1)
  [1]=>
  int(2)
}

作用域

PHP
<?php
$global = "全局";

function test(): void
{
    // echo $global;              // 警告:未定义,函数内看不到全局变量
    global $global;               // 用 global 声明
    echo $global, "\n";

    $local = "局部";
    echo $local, "\n";
}

test();
// echo $local;                   // 警告:函数外看不到局部变量

// 更好的做法:用参数传
function better(string $g): void
{
    echo $g, "\n";
}
better($global);
Output
全局
局部
全局
The global keyword makes data flow hard to follow. Pass data via parameters and return values; reserve global for legacy code.

static 变量

PHP
<?php
function counter(): int
{
    static $n = 0;        // 只初始化一次,跨调用保持
    $n++;
    return $n;
}

echo counter(), counter(), counter(), "\n";

function normal(): int
{
    $n = 0;               // 每次都重置
    return ++$n;
}
echo normal(), normal(), "\n";
Output
123
11

引用赋值

PHP
<?php
$a = 1;
$b = $a;              // 值复制
$b = 2;
echo $a, "\n";        // 1

$c = 1;
$d = &$c;             // 引用,两个名字指向同一份数据
$d = 2;
echo $c, "\n";        // 2

// 函数引用参数
function addOne(array &$arr): void
{
    $arr[] = 99;
}
$list = [1, 2];
addOne($list);
print_r($list);
Output
1
2
Array
(
    [0] => 1
    [1] => 2
    [2] => 99
)

Objects behave reference-like (handles) while arrays and scalars are copied. Passing a large array copies it — use & or a readonly type to avoid that.

可变变量与检测

PHP
<?php
$field = "name";
$$field = "张三";       // 等价于 $name = "张三"
echo $name, "\n";

// 变量检测
$defined = 1;
var_dump(isset($defined));
var_dump(isset($undefined));
var_dump(empty($defined));        // 1 算「非空」
var_dump(empty(""));              // 空字符串算「空」

echo gettype($defined), "\n";

// 类型转换
$num = "42";
var_dump((int) $num);
var_dump(is_numeric("42abc"));
Output
张三
bool(true)
bool(false)
bool(false)
bool(true)
integer
int(42)
bool(false)
FunctionMeaning
isset($x)存在且不为 null
empty($x)0 "" null false [] 都算空
unset($x)销毁变量
gettype($x)取类型名
is_numeric是否数字或数字字符串
empty() treats 0 and "0" as empty — a frequent bug when a quantity of 0 is read as "not filled". To distinguish, use isset() or !== ''.

Friends & Partners