蓝色天空.知识 · 实践 · 创造
我的收藏
PHP 教程目录 95章
课程介绍
PHP / LEARN BY DOING

PHP 数据类型

逐一核对 PHP 八大数据类型(String、Integer、Float、Boolean、Array、Object、NULL、Resource)的定义规则、var_dump 输出与 PHP 8 资源对象化演进。

学完这一章,你能够

  • 逐一核对 PHP 八大数据类型(String、Integer、Float、Boolean、Array、Object、NULL、Resource)的定义规则、var_dump 输出与 PHP 8 资源对象化演进。

PHP 八大数据类型总览与字符串、布尔型

PHP 变量可以保存不同类型的数据以适配不同运算。语言核心共支持 8 种主要数据类型:4 种标量类型——String(字符串)、Integer(整型)、Float(浮点型)、Boolean(布尔型),2 种复合类型——Array(数组)、Object(对象),以及 2 种特殊类型——NULL(空值)与 Resource(资源类型)。

字符串是一段字符序列,可用单引号或双引号包裹;布尔型仅包含 `true` 与 `false` 两个值,常用于条件判断与逻辑分支。本站 PHP 8.4.27 实测 `"Hello world!" === 'Hello world!'` 为 `true`(类型 `string`),`var_dump(true)` 与 `var_dump(false)` 分别输出 `bool(true)` 与 `bool(false)`。

整型进制规则与浮点型表示

整型是没有小数部分的数字:至少包含一位 `0-9` 数字、不可含逗号或空格、无小数点,可正可负,支持十进制、十六进制(`0x` 前缀)与八进制(`0` 前缀,PHP 8.1 起新增更清晰的 `0o` 前缀,此外还支持 `0b` 二进制)。调用 `var_dump()` 可同时输出变量类型与值。本站实测 `5985`、`-345`、`0x8C`、`047`、`0o47` 的 `var_dump` 结果分别为 `int(5985)`、`int(-345)`、`int(140)`、`int(39)`、`int(39)`。

浮点型用于表示带小数部分或科学计数法指数形式的数值。本站实测 `10.365`、`2.4e3` 与 `8E-5`,`var_dump()` 分别输出 `float(10.365)`、`float(2400)` 与 `float(8.0E-5)`。

数组、对象与 NULL 空值

数组能在单个变量中按索引或键名组织多个值。本站实测 `["Volvo", "BMW", "Toyota"]` 类型为 `array`、长度 `3`、首项为 `Volvo`(数组排序与遍历将在后续数组章节详解)。

对象由 `class` 类声明定义其属性与方法,再经 `new` 实例化使用;类方法中的 `$this` 始终指向当前对象实例本身(现代 PHP 推荐使用 `public string $color;` 替代早期 PHP 4 的 `var` 写法)。本站实测 `new Car()` 默认调用 `whatColor()` 返回 `'green'`,`new Car('blue')` 返回 `'blue'`。

`NULL` 表示变量没有值,且其唯一数据类型即为 `NULL`,可用于区分“未赋值/空值”与空字符串 `""`;将已有变量设为 `null` 即可清空数据。本站实测将 `$val = "Hello world!"` 改为 `$val = null` 后,`var_dump($val)` 输出 `NULL`、`is_null($val)` 为 `true` 且 `$val !== ''` 为 `true`。

资源类型与 PHP 8 历史接口迁移

Resource(资源)是保存外部句柄引用的特殊变量(常见如打开的文件流),将普通类型强制转为资源毫无意义。`get_resource_type(resource $handle): string` 返回资源类型名,传入非资源值在 PHP 8 中会抛出 `TypeError`。需要特别说明历史演进:早期资料中的 `mysql_connect()` 与 `new_xmldoc()` 已在 PHP 7/8 中移除(现代应迁移至 PDO/MySQLi 与 DOMDocument/SimpleXML),而 GD 图像句柄自 PHP 8.0 起也已演进为 `GdImage` 对象而非 resource。本站 PHP 8.4.27 实测 `fopen('php://memory', 'r+')` 返回 `stream` 资源,`get_resource_type('not-a-resource')` 精确抛出 `TypeError`,`imagecreatetruecolor(4, 4)` 返回 `GdImage` 对象且 `is_resource()` 为 `false`。

实测 PHP 8.4 全部八大数据类型、var_dump 输出与资源/GdImage 演进

含完整源码 · 166 行
展开查看收起
php
<?php
declare(strict_types=1);

class Car
{
    public string $color;

    public function __construct(string $color = 'green')
    {
        $this->color = $color;
    }

    public function whatColor(): string
    {
        return $this->color;
    }
}

function captureDump(mixed $value): string
{
    ob_start();
    var_dump($value);
    return trim(str_replace("\r\n", "\n", (string) ob_get_clean()));
}

$cases = [];

// Case 1: String (single/double quotes) and Boolean types
$sDouble = "Hello world!";
$sSingle = 'Hello world!';
$bTrue = true;
$bFalse = false;
$sbActual = [
    'strings_identical' => $sDouble === $sSingle,
    'string_type' => gettype($sDouble),
    'bool_true_dump' => captureDump($bTrue),
    'bool_false_dump' => captureDump($bFalse),
    'branch_result' => $bTrue && !$bFalse ? 'yes' : 'no',
];
$sbExpected = [
    'strings_identical' => true,
    'string_type' => 'string',
    'bool_true_dump' => 'bool(true)',
    'bool_false_dump' => 'bool(false)',
    'branch_result' => 'yes',
];
$cases[] = [
    'name' => 'string_and_boolean_types',
    'passed' => $sbActual === $sbExpected,
    'expected' => $sbExpected,
    'actual' => $sbActual,
];

// Case 2: Integer bases (dec, neg, hex, octal, PHP 8.1+ 0o) and Float notation
$numActual = [
    'dec' => captureDump(5985),
    'neg' => captureDump(-345),
    'hex' => captureDump(0x8C),
    'oct_legacy' => captureDump(047),
    'oct_php81' => captureDump(0o47),
    'float_dec' => captureDump(10.365),
    'float_exp_pos' => captureDump(2.4e3),
    'float_exp_neg' => captureDump(8E-5),
];
$numExpected = [
    'dec' => 'int(5985)',
    'neg' => 'int(-345)',
    'hex' => 'int(140)',
    'oct_legacy' => 'int(39)',
    'oct_php81' => 'int(39)',
    'float_dec' => 'float(10.365)',
    'float_exp_pos' => 'float(2400)',
    'float_exp_neg' => 'float(8.0E-5)',
];
$cases[] = [
    'name' => 'integer_bases_and_float_notation',
    'passed' => $numActual === $numExpected,
    'expected' => $numExpected,
    'actual' => $numActual,
];

// Case 3: Array and Object types ($this binding in Car class)
$cars = ["Volvo", "BMW", "Toyota"];
$defaultCar = new Car();
$blueCar = new Car('blue');
$aoActual = [
    'array_count' => count($cars),
    'array_type' => gettype($cars),
    'first_car' => $cars[0],
    'object_type' => gettype($defaultCar),
    'default_color' => $defaultCar->whatColor(),
    'custom_color' => $blueCar->whatColor(),
];
$aoExpected = [
    'array_count' => 3,
    'array_type' => 'array',
    'first_car' => 'Volvo',
    'object_type' => 'object',
    'default_color' => 'green',
    'custom_color' => 'blue',
];
$cases[] = [
    'name' => 'array_and_object_types',
    'passed' => $aoActual === $aoExpected,
    'expected' => $aoExpected,
    'actual' => $aoActual,
];

// Case 4: NULL clearing vs empty string
$val = "Hello world!";
$val = null;
$nullActual = [
    'dump' => captureDump($val),
    'type' => gettype($val),
    'is_null' => is_null($val),
    'strict_not_empty_str' => $val !== '',
];
$nullExpected = [
    'dump' => 'NULL',
    'type' => 'NULL',
    'is_null' => true,
    'strict_not_empty_str' => true,
];
$cases[] = [
    'name' => 'null_clearing_vs_empty_string',
    'passed' => $nullActual === $nullExpected,
    'expected' => $nullExpected,
    'actual' => $nullActual,
];

// Case 5: Resource stream handle, get_resource_type(), TypeError on non-resource, and PHP 8 GdImage object
$fp = fopen('php://memory', 'r+');
$isRes = is_resource($fp);
$resType = get_resource_type($fp);
fclose($fp);

$invalidThrown = false;
try {
    /** @noinspection PhpParamsInspection */
    get_resource_type('not-a-resource');
} catch (TypeError) {
    $invalidThrown = true;
}

$gd = imagecreatetruecolor(4, 4);
$resActual = [
    'stream_is_resource' => $isRes,
    'stream_resource_type' => $resType,
    'non_resource_throws_type_error' => $invalidThrown,
    'gd_is_object_in_php8' => $gd instanceof GdImage && !is_resource($gd),
];
$resExpected = [
    'stream_is_resource' => true,
    'stream_resource_type' => 'stream',
    'non_resource_throws_type_error' => true,
    'gd_is_object_in_php8' => true,
];
$cases[] = [
    'name' => 'resource_stream_and_php8_objects',
    'passed' => $resActual === $resExpected,
    'expected' => $resExpected,
    'actual' => $resActual,
];

echo json_encode(['version' => PHP_VERSION, 'cases' => $cases], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
验证字符串、布尔、多进制整型、指数浮点、数组、Car 对象、NULL 清空、stream 资源类型及非资源触发 TypeError 与 GdImage 对象。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a1232.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:PHP

课程关联工程包(登记关联95章) · 含当前章节或实例 · mbskycom202612a1232.zip

下载课程关联工程包:PHP

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1236.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

`fopen()` 仍返回类型为 `stream` 的 `resource` 句柄;`imagecreatetruecolor()` 自 PHP 8.0 起返回 `GdImage` 对象(`is_resource()` 为 `false`)。`mysql_*` 扩展早在 PHP 7.0 即已彻底移除,现代项目应使用支持预处理语句的 `PDO` 或 `MySQLi`。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习