05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

A More Complex Example<br />

Here’s an example that forces the function to fetch only the first three parameters: an<br />

array, a Boolean, and an object. We are using 'O' and also supplying an object type,<br />

which we can check in case we want to accept only a certain class of object.<br />

zval *arr;<br />

zend_bool b;<br />

zval *obj;<br />

zend_class_entry obj_ce;<br />

if (zend_parse_parameters(3 TSRMLS_CC, "abO", &arr, &b, &obj,<br />

obj_ce) == FAILURE) {<br />

return;<br />

}<br />

Forcing them to fetch only three parameters is useful for functions that can take a<br />

variable amount of parameters. You can then check the total number of arguments<br />

passed to see if there are any further arguments to process.<br />

An Example with Variable Argument List<br />

The following code illustrates how to process a variable argument list. It uses zend_<br />

parse_parameters( ) to fetch the first argument and reads further arguments into a<br />

zval *** array, then puts all the passed parameters into a <strong>PHP</strong> array and returns<br />

them:<br />

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

long arg;<br />

zval ***args;<br />

int i, argc = ZEND_NUM_ARGS( );<br />

if (zend_parse_parameters(1 TSRMLS_CC, "l", &arg) == FAILURE) return;<br />

array_init(return_value);<br />

add_index_long(return_value, 0, arg);<br />

if(argc>1) {<br />

args = (zval ***)emalloc(argc * sizeof(zval **));<br />

if(zend_get_parameters_array_ex(argc, args) == FAILURE) {<br />

efree(args);<br />

return;<br />

}<br />

for(i = 1; i < argc; i++) {<br />

zval_add_ref(args[i]);<br />

add_index_zval(return_value,i, *args[i]);<br />

}<br />

efree(args);<br />

}<br />

}<br />

The zval_add_ref( ) call increments the reference count of the zval container. It is<br />

explained in detail in the “References” section.<br />

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

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.<br />

Parameter Handling | 337

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

Saved successfully!

Ooh no, something went wrong!