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, preallocated
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 ...
Get Programming PHP now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.