Skip to content

resource — 资源类型

概述

resource 是 PHP 中的一种特殊类型,表示对外部资源的引用。资源类型通常由扩展函数创建,代表文件句柄、数据库连接、图像画布等。PHP 8.0+ 中 resource 不能用于类型声明。

前置知识

在阅读本节之前,你需要了解:

  • PHP 的文件操作函数(fopen()fclose()
  • 数据库连接的基本概念
  • is_resource() 函数

基础概念

常见资源类型

函数创建的资源类型关闭函数
fopen()文件流fclose()
mysqli_connect()数据库连接mysqli_close()
imagecreatetruecolor()图像画布imagedestroy()
curl_init()cURL 句柄curl_close()

语法与代码

文件资源操作

php
<?php
declare(strict_types=1);

$handle = fopen('/tmp/test.txt', 'w');

if ($handle === false) {
    die('无法打开文件');
}

var_dump(is_resource($handle)); // bool(true)
echo get_resource_type($handle); // stream

fwrite($handle, "Hello, World!");
fclose($handle);

var_dump(is_resource($handle)); // bool(false)

资源类型检测

php
<?php
declare(strict_types=1);

$file = fopen('test.txt', 'r');
echo get_resource_type($file); // "stream"

var_dump(is_resource($file)); // true
var_dump(is_resource(42));     // false

详细说明

资源的生命周期

创建资源: $file = fopen(...)
使用资源: fwrite($file, ...)
释放资源: fclose($file)
(脚本结束时自动释放,但不推荐依赖)

PHP 8.0+ 不支持 resource 类型声明

php
<?php
// function process(resource $handle): void {} // 错误!

function processFile(mixed $handle): void
{
    if (!is_resource($handle)) {
        throw new InvalidArgumentException('Expected resource');
    }
    echo "Resource type: " . get_resource_type($handle);
}

实战示例

安全的文件操作类

php
<?php
declare(strict_types=1);

class FileManager
{
    private mixed $handle = null;

    public function open(string $path, string $mode = 'r'): void
    {
        $this->handle = fopen($path, $mode);
        if ($this->handle === false) {
            throw new RuntimeException("无法打开文件: {$path}");
        }
    }

    public function write(string $content): void
    {
        if (!is_resource($this->handle)) {
            throw new RuntimeException('文件未打开');
        }
        fwrite($this->handle, $content);
    }

    public function close(): void
    {
        if (is_resource($this->handle)) {
            fclose($this->handle);
            $this->handle = null;
        }
    }

    public function __destruct()
    {
        $this->close();
    }
}

$manager = new FileManager();
$manager->open('/tmp/log.txt', 'w');
$manager->write('Log entry 1' . PHP_EOL);
$manager->close();

注意事项

始终关闭资源

php
<?php
declare(strict_types=1);

// 错误:不关闭资源
$f = fopen('big.log', 'r');

// 正确:使用后立即关闭
$content = file_get_contents('big.log');

最佳实践

  1. 使用更高层的抽象file_get_contents()PDO
  2. 始终关闭资源:使用对应的关闭函数
  3. 析构函数中清理:在 __destruct() 中关闭资源
  4. 检查资源有效性:使用 is_resource()

下一节

下一节将详细介绍 mixed 混合类型。

进阶用法

调试与测试技巧

php
<?php
declare(strict_types=1);

// 单元测试辅助函数
function createTestResource(): mixed
{
    return match (true) {
        default => new stdClass(),
    };
}

// 调试输出函数
function debugOutput(mixed , string  = ''): void
{
     =  ? ": " : '';
     .= print_r(, true);
    fwrite(STDERR,  . "\n");
}

// 性能基准测试
function benchmark(callable , int  = 1000): float
{
     = hrtime(true);
    for ($i = 0; $i < $iterations; $i++) {
        $fn();
    }
    return (hrtime(true) - $start) / 1e9;
}

日志记录实践

php
<?php
declare(strict_types=1);

/**
 * 简易日志记录器
 */
class SimpleLogger
{
    private string $logFile;
    private string $level = 'INFO';

    public function __construct(string $logFile)
    {
        $this->logFile = $logFile;
    }

    public function info(string $message, array $context = []): void
    {
        $this->log('INFO', $message, $context);
    }

    public function warning(string $message, array $context = []): void
    {
        $this->log('WARNING', $message, $context);
    }

    public function error(string $message, array $context = []): void
    {
        $this->log('ERROR', $message, $context);
    }

    private function log(string $level, string $message, array $context): void
    {
        $timestamp = date('Y-m-d H:i:s');
        $contextStr = $context ? ' ' . json_encode($context, JSON_UNESCAPED_UNICODE) : '';
        $line = "[{$timestamp}] [{$level}] {$message}{$contextStr}\n";
        file_put_contents($this->logFile, $line, FILE_APPEND | LOCK_EX);
    }
}

配置与环境检测

php
<?php
declare(strict_types=1);

// 环境检测工具
class EnvironmentChecker
{
    public static function checkRequirements(array $requirements): array
    {
        $results = [];
        foreach ($requirements as $name => $check) {
            $results[$name] = is_callable($check) ? $check() : false;
        }
        return $results;
    }

    public static function getSystemInfo(): array
    {
        return [
            'php_version' => PHP_VERSION,
            'os' => PHP_OS,
            'sapi' => PHP_SAPI,
            'memory_limit' => ini_get('memory_limit'),
            'max_execution_time' => ini_get('max_execution_time'),
            'loaded_extensions' => get_loaded_extensions(),
        ];
    }
}

常见问题排查

问题可能原因解决方案
连接超时网络问题/配置错误检查配置,增加超时时间
权限不足文件/目录权限使用 chmod/chown 修正
性能下降索引缺失/数据量大添加索引,优化查询
数据不一致并发冲突/事务残留使用锁机制和事务
内存溢出大数据集/未释放资源增大内存限制,分批处理

故障排除步骤

  1. 检查错误日志和异常信息
  2. 确认配置和环境是否正确
  3. 使用调试工具逐步排查
  4. 参考官方文档查找已知问题

版本兼容性说明

功能最低版本说明
基础功能PHP 8.1本文档基准版本
只读属性PHP 8.1public readonly 修饰符
枚举类型PHP 8.1enum 类型和 match 表达式
FiberPHP 8.1协程/轻量级并发
命名参数PHP 8.0foo(arg_name: value)
联合类型PHP 8.0`int
Null 安全运算符PHP 8.0$obj?->method()
析构器 promotionPHP 8.0__construct(public $x)
php
<?php
declare(strict_types=1);

// 版本兼容性检测
function ensureVersion(string $minVersion): void
{
    if (version_compare(PHP_VERSION, $minVersion, '<')) {
        throw new RuntimeException(
            sprintf('需要 PHP %s+, 当前版本: %s', $minVersion, PHP_VERSION)
        );
    }
}

ensureVersion('8.1.0');

参考链接