05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Returning Values<br />

Knowing how to get data into a function is only one side of the problem—how do<br />

you get it out? This section shows you how to return values from an extension function,<br />

from simple strings or numbers all the way up to arrays and objects.<br />

Simple Types<br />

Returning a value from a function back to the script involves populating the special,<br />

preallocated return_value container. For example, this returns an integer:<br />

<strong>PHP</strong>_FUNCTION(foo) {<br />

Z_LVAL_P(return_value) = 99;<br />

Z_TYPE_P(return_value) = IS_LONG;<br />

}<br />

Since returning a single value is such a common task, there are a number of convenience<br />

macros to make it easier. The following code uses a convenience macro to<br />

return an integer:<br />

<strong>PHP</strong>_FUNCTION(foo) {<br />

RETURN_LONG(99);<br />

}<br />

The RETURN_LONG( ) macro fills in the container and immediately returns. If for some<br />

reason we wanted to populate the return_value container and not return right away,<br />

we could use the RETVAL_LONG( ) macro instead.<br />

Returning a string is almost as simple with the convenience macros:<br />

<strong>PHP</strong>_FUNCTION(rt13) {<br />

RETURN_STRING("banana", 1);<br />

}<br />

The last argument specifies whether or not the string needs to be duplicated. In that<br />

example it obviously does, but if we had allocated the memory for the string using an<br />

emalloc( ) or estrdup( ) call, we wouldn’t need to make a copy:<br />

<strong>PHP</strong>_FUNCTION(rt13) {<br />

char *str = emalloc(7);<br />

strcpy(str, "banana");<br />

RETURN_STRINGL(str, 6, 0);<br />

}<br />

Here we see an example of doing our own memory allocation and also using a version<br />

of the RETURN macro that takes a string length. Note that we do not include the<br />

terminating NULL in the length of our string.<br />

The available RETURN-related convenience macros are listed in Table 14-4.<br />

338 | Chapter 14: Extending <strong>PHP</strong><br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!