Parameter Handling

As we learned in the previous section on the pval/zval container, there are at least two ways to accept and parse arguments to PHP functions you write. We will concentrate on the higher-level zend_parse_parameters( ) function here.

There are two versions of the function, prototyped like this in C:

    int zend_parse_parameters(int num_args TSRMLS_DC, char *type_spec, ...);
    int zend_parse_parameters_ex(int flags, int num_args TSRMLS_DC,
      char *type_spec, ...);

They differ only in that the ex, or expanded, version of the function contains a flags parameter. The only flag currently supported is ZEND_PARSE_PARAMS_QUIET, which inhibits warnings from supplying an incorrect number or type of arguments.

Both parameter-parsing functions return either SUCCESS or FAILURE. The functions take any number of extra arguments (pointers to variables whose values are assigned by the parsing function). On failure the return_value of the function is automatically set to FALSE, so you can simply return from your function on a failure.

The most complex part of these functions is the type_spec string you pass them. Here’s the relevant part of our rot13 example:

    char *arg = NULL;
    int arg_len, argc = ZEND_NUM_ARGS( );
    if (zend_parse_parameters(argc TSRMLS_CC, "s/", &arg, &arg_len) == FAILURE)
        return;

We first get the number of arguments passed to this function by calling the ZEND_NUM_ARGS( ) macro. We pass this number along with a type_spec string of "s/" and then the address of a char * and the ...

Get Programming PHP, 2nd Edition 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.