O'Reilly logo

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

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Returning Values

Knowing how to get data into a function is only one side of the problem—how do you get it out? This section shows you how to return values from an extension function, from simple strings or numbers all the way up to arrays and objects.

Simple Types

Returning a value from a function back to the script involves populating the special, pre-allocated return_value container. For example, this returns an integer:

    PHP_FUNCTION(foo) {
        Z_LVAL_P(return_value) = 99;
        Z_TYPE_P(return_value) = IS_LONG;
    }

Since returning a single value is such a common task, there are a number of convenience macros to make it easier. The following code uses a convenience macro to return an integer:

    PHP_FUNCTION(foo) {
        RETURN_LONG(99);
    }

The RETURN_LONG( ) macro fills in the container and immediately returns. If for some reason we wanted to populate the return_value container and not return right away, we could use the RETVAL_LONG( ) macro instead.

Returning a string is almost as simple with the convenience macros:

    PHP_FUNCTION(rt13) {
        RETURN_STRING("banana", 1);
    }

The last argument specifies whether or not the string needs to be duplicated. In that example it obviously does, but if we had allocated the memory for the string using an emalloc( ) or estrdup( ) call, we wouldn’t need to make a copy:

    PHP_FUNCTION(rt13) {
        char *str = emalloc(7);
        strcpy(str, "banana");
        RETURN_STRINGL(str, 6, 0);
    }

Here we see an example of doing our own memory allocation and also using a version of the RETURN macro that takes ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required