如何在php中存储资源类型?它是内存中的字符串还是某种结构? 在文档中
A resource is a special variable, holding a reference to an external resource.
它在 php 环境下如何工作?
最佳答案
通过基本结构 ZVAL 在 PHP 实现中的类型。 每种类型都是结构 ZVAL(Zend 值)。
据我们所知
A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions.
例如fopen
返回类型resurce。
$fp = fopen('/proc/cpuinfo', 'r');
$fp - 是资源类型,表示在php核心中已经按结构创建了组成数据:
struct _zend_resource {
zend_refcounted_h gc;
int handle;
int type;
void *ptr;
};
其中 zend_refcounted_h
- 我们类型的 header ,它用于内存管理并表示哈希;
handle
是引擎内部使用的一个整数,用于将资源定位到内部资源表中。 Php 在创建资源的过程中创建它。
type
用于将相同类型的资源重新组合在一起。这意味着我们需要调用资源的析构函数,它可以帮助我们找到注册的析构函数。
ptr
是我们的抽象数据。
舞台创建资源:
1. 用zend_register_list_destructors_ex()
注册析构函数。它需要在垃圾收集器中清理内存。
2. 注册新资源 zend_register_resource()
并将指针附加到析构函数。返回的是我们的类型 zend_register_list_destructors_ex()
完整示例。
static void file_destructor(zend_resource *rsrc)
{
fclose((FILE *)rsrc->ptr);
}
type = zend_register_list_destructors_ex(
file_destructor, // pointer to destructor
NULL, // pointer to destructor for persistent resource, that non deleted after end request (example BD connection resource)
"file_resource", // name
module_number // PHP extension number
);
fp = fopen("/proc/cpuinfo", "r");
file_resource = zend_register_resource((void *)fp, type);
ZVAL_RES(&my_val, file_resource);
Resource types are just a way for the engine to mix different kind of resources (of type “file”, “gzip” or even “mysql connection”) into the same resource table.
有关资源类型、创建、删除和工作的更多详细信息 phpinternalsbook
关于php - 如何在php中存储资源类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54026901/