资源

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

注: 资源类型是 PHP 4 引进的。

参见 get_resource_type()

转换为资源

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

释放资源

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

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


add a note add a note User Contributed Notes
evildictaitor at hotmail dot com
17-Aug-2004 01:25
In response to yasuo_ohgaki, the reason for the inability of the $_SESSION[] variable to hold references is because a session is just a serialize()'d version of it's member variables saved under a unique filename, with this filename following the user around.

$_SESSION[] is therefore limited by the constraints of the serialize() function

Although this is not <i>strictly</i> true, ($_SESSION does some handling to convert messy variables (e.g. "s and ;s)) it cannot store resources due to the serialise() function's dependancy
isaac at chexbox dot com
23-Jun-2002 04:37
For the the oblivious: An example of a resource would be a mysql database connection.

$result = mysql_connect("localhost", "username", "pass");
//$result variable is a resource.

print $result;
//will print: Resource ID#1, or something similar
yasuo_ohgaki at hotmail dot com
21-May-2001 05:04
Resource type values are not saved in session variables. (Programmer must re-initialize resource type in session var anyway, because values held by resources are useless connection to connection)