Skip to Content
Programming PHP
book

Programming PHP

by Rasmus Lerdorf, Kevin Tatroe
March 2002
Intermediate to advanced
528 pages
21h 29m
English
O'Reilly Media, Inc.
Content preview from Programming PHP

Resources

A resource is a generic data container that can hold any sort of data. An internal list mechanism keeps track of your resources, which are referenced through simple resource identifiers.

Use resources in your extensions when the extension is providing an interface to something that needs cleanup. When the resource goes out of scope or your script ends, your destructor function for that resource is called, and you can free memory, close network connections, remove temporary files, etc.

Here’s a simple little example where we tie our resource to a trivial struct that contains only a string and an integer (name and age, in this case):

static int le_test;
  
typedef struct _test_le_struct {
    char *name;
    long age;
} test_le_struct;

The struct can contain anything: a file pointer, a database connection handle, etc. The destructor function for our resource looks like this:

static void _php_free_test(zend_rsrc_list_entry *rsrc TSRMLS_DC) {
    test_le_struct *test_struct = (test_le_struct *)rsrc->ptr;
  
    efree(test_struct->name);
    efree(test_struct);
}

In your MINIT( ) function, add this line to register your destructor for the le_test resource:

le_test = zend_register_list_destructors_ex(_php_free_test, NULL, "test", 
  module_number);

Now, here’s a fictitious my_init( ) function that initializes the data associated with the resource. It takes a string and an integer (name and age):

PHP_FUNCTION(my_init) { char *name = NULL; int name_len, age; test_le_struct *test_struct; if (zend_parse_parameters(ZEND_NUM_ARGS( ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming PHP, 3rd Edition

Programming PHP, 3rd Edition

Rasmus Lerdorf, Kevin Tatroe, Peter MacIntyre
Programming PHP, 2nd Edition

Programming PHP, 2nd Edition

Rasmus Lerdorf, Kevin Tatroe, Peter MacIntyre
Clean Code in PHP

Clean Code in PHP

Carsten Windler, Alexandre Daubois

Publisher Resources

ISBN: 1565926102Supplemental ContentCatalog PageErrata