Laravel Live Denmark 2026

Resource 资源类型

资源 resource 是一种特殊变量,保存了到外部资源的一个引用。资源是通过专门的函数来建立和使用的。所有这些函数及其相应资源类型见附录

参见 get_resource_type()

转换为资源

由于资源类型变量保存有为打开文件、数据库连接、图形画布区域等的特殊句柄,因此将其它类型的值转换为资源没有意义。

释放资源

引用计数系统是 Zend 引擎的一部分,可以自动检测到一个资源不再被引用了(和 Java 一样)。这种情况下此资源使用的所有外部资源都会被垃圾回收系统释放。因此,很少需要手工释放内存。

注意: 持久数据库连接比较特殊,它们不会被垃圾回收系统销毁。参见数据库永久连接一章。

添加备注

用户贡献的备注 1 note

up
1
mrmhmdalmalki at gmail dot com
8 hours ago
The resource is not a type you can create; it is a PHP internal type that PHP uses to refer to some variables.

For example, 

You have a number 5.5, which is a Float, and you can convert it to an int type, but you cannot convert it to a resource.

A resource type is used for external resources, like files or database connections, as shown below:

<?php

// a normal variable
$file_resource = fopen("normal_file.txt", "r");

// after we assigned an external file to that variable using the function fopen,
// PHP starts dealing with the file, and since it is an external resource,
// PHP makes the type of the variable a resource that refers to that operation

var_dump($file_resource);

// the previous var_dump returned bool(false),
// because there was no file that PHP could open.
// and it gave me this warning:
// PHP Warning: fopen(normal_file.txt): Failed to open stream: No such file or directory

// now I am trying to open an existing file
$file_resource = fopen("existed_file.txt", "r");

// then check the type:
var_dump($file_resource);

// it gives this:
// resource(5) of type (stream)
// now the variable's type is resource

?>
To Top