Search code examples
phpcphp-extension

PHP Extension: How to return a new class object


I am creating an extension that has multiple classes and some of them have methods that should return instances of another class. This is for PHP 7+ and not for anything else.

For example, I need the PHP code to be something like this (I'm creating an ALPM PHP extension)...

$handle_object = new Handle("/", "/var/lib/pacman");
$db_object = $handle_object->get_localdb() /* this returns a Db object */

The code I have so far is...

PHP_METHOD(Handle, get_localdb) {
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "") == FAILURE) {
        RETURN_NULL()
    }

    zval *db_obj = (zval*)emalloc(sizeof(zval));
    handle_object *intern = Z_HANDLEO_P(getThis());

    object_init_ex(db_obj, alpm_ce_db);
}

I have no clue if I'm on the right track or far from it.

For more code from the project (so far), I have posted it up on gist (https://gist.github.com/markzz/27b0aa1123d61a5f9d80ee3aea390f20).


Solution

  • With help from the php chat (thanks guys)!

    PHP_METHOD(Handle, get_localdb) {
        if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "") == FAILURE) {
            RETURN_NULL()
        }
    
        handle_object *intern = Z_HANDLEO_P(getThis());
        db_object *db;
        object_init_ex(return_value, alpm_ce_db);
        db = Z_DBO_P(return_value);
        db->db = alpm_get_localdb(intern->handle);
    }