21.4 Returning Arrays and Objects from Functions


You want to return an array or an object from a function.

Technique

To initialize the return value as an array, use the array_init() function and add different values to it through the different array-manipulation functions available in the Zend API.

Returning a numerically indexed array:

 PHP_FUNCTION(somefunc) {     int i;     if (array_init(return_value) == FAILURE) {         php_error(E_WARNING, "cannot initialize return value");         RETURN_FALSE;     }     for (i = 0; i < 10; i++) {         add_next_index_long(return_value, i);     }     add_next_index_string(return_value, "Hello World", 1);     add_next_index_string(return_value, "Goodbye World", 1); } 

Returning a string indexed (associative) array:

 PHP_FUNCTION(somefunc) {     if (array_init(return_value) == FAILURE) {         php_error(E_WARNING, "Cannot initialize return value");         RETURN_FALSE;     }     add_assoc_string(return_value, "key1", "keyValue", 1);     add_assoc_stringl(return_value, "key2", "keyValue", strlen("keyValue"), 1);     add_assoc_long(return_value, "key3", 14);     add_assoc_double(return_value, "key4" 3.23243); } 

Returning an object from a function:

 PHP_FUNCTION(somefunc) {     if (object_init(return_value) == FAILURE) {         php_error(E_WARNING, "Cannot initialize return value from somefunc");         RETURN_FALSE;     }     add_property_string(return_value, "key1", "keyValue", 1);     add_property_double(return_value, "key2", 4.5); } 

Comments

Arrays

Whether the array is an associative array or a numerically indexed array, the steps for returning the array are identical (in a theoretical sense). First, you initialize the array with the array_init() function and then you add values to the array. Adding values to the array is where the implementation differs .

When adding elements to the numerically indexed array, we use the add_next_index_* functions, which enable you to add new items to a numerically indexed array. If the element is a string, you can use the add_next_index_string() function or the add_ next_index_stringl() function. If the element is a long, use the add_next_index_ long() function; and if the element is a double, use the add_next_index_double() function.

To add elements with string keys, use the add_assoc_*() functions, which are similar to their numerical counterparts.

Objects

Returning objects is almost the same as returning arrays, except that you call object_init() on the zval and use add_property_*() functions instead of add_assoc_*() ones.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net