PHP 数据类型

八种类型、`var_dump` 看类型、以及类型声明的严格模式。

Beginner
Key PointsPHP 是动态类型语言,变量类型由值决定,可以随时变。

八种类型

TypeExampleNote
string"abc"字节序列,非 Unicode
int42平台相关,通常 64 位
float3.14双精度,也叫 double
booltrue / false不区分大小写
array[1, 2]有序映射,键可以是整数或字符串
objectnew Foo()类实例
nullnull表示无值
resourcefopen(...)外部资源句柄
PHP
<?php
$values = [
    "字符串" => "abc",
    "整数"   => 42,
    "浮点"   => 3.14,
    "布尔"   => true,
    "数组"   => [1, 2],
    "对象"   => new stdClass(),
    "空"     => null,
];

foreach ($values as $label => $v) {
    printf("%-8s %s\n", $label, gettype($v));
}
Output
字符串   string
整数     integer
浮点     double
布尔     boolean
数组     array
对象     object
空       NULL

数组其实是有序映射

PHP
<?php
// 索引数组
$list = [10, 20, 30];
echo $list[0], "\n";

// 关联数组
$user = ["name" => "张三", "age" => 28];
echo $user["name"], "\n";

// 混合键,保持插入顺序
$mixed = [
    "a" => 1,
    5 => "five",
    "b" => 2,
    6 => "six",
];
print_r($mixed);

// 键会自动转换
$auto = [
    "1" => "字符串 1",     // 变成整数 1
    true => "true",       // 变成 1(覆盖上一个)
    1.7 => "float",       // 变成 1(再覆盖)
];
print_r($auto);
Output
10
张三
Array
(
    [a] => 1
    [5] => five
    [b] => 2
    [6] => six
)
Array
(
    [1] => float
)

PHP array keys are int or string only. "1" becomes 1, true becomes 1, 1.7 truncates to 1 — so all three assignments hit the same key.

类型声明与严格模式

PHP
<?php
declare(strict_types=1);      // 必须放在文件第一行

function add(int $a, int $b): int
{
    return $a + $b;
}

echo add(1, 2), "\n";

// 严格模式下不转换
try {
    echo add("1", "2"), "\n";
} catch (TypeError $e) {
    echo "类型错误:", $e->getMessage(), "\n";
}
Output
3
类型错误:add(): Argument #1 ($a) must be of type int, string given

Without declare(strict_types=1) PHP coerces: "1" becomes 1 and "abc" errors. Strict mode refuses to convert at all and throws TypeError.

Strict mode is per file and applies at the call site, not the callee — a library cannot force callers to be strict. Enable it in every new file.

类型转换

PHP
<?php
var_dump((int) "42abc");
var_dump((int) "abc");
var_dump((float) "3.14abc");
var_dump((bool) "0");
var_dump((bool) "0.0");
var_dump((bool) []);
var_dump((string) 42);
var_dump((array) "x");
var_dump((int) true);
Output
int(42)
int(0)
float(3.14)
bool(false)
bool(true)
bool(false)
string(2) "42"
array(1) {
  [0]=>
  string(1) "x"
}
int(1)
(bool) "0.0" is true because "0.0" is neither "" nor "0". PHP's rule: false, 0, 0.0, "", "0", [] and null are falsy — everything else is true.

Friends & Partners