PHP Extensions: Accepting parameters.

10 May

While building extension, you will be writing functions. Those may be standalone functions or function defined in the classes. Whatever is the case, most of the functions accept parameters. In c we can pass parameters as

void sum(int a, int b)

{

printf(“a + b = %d”, a+b);

}

The above method accept two parameters a and b and print the sum of these values.

While building the php extension, the above function will look like this.

PHP_FUNCTION(sum)

{

long a, b;

if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC,”ll”, &a, &b) == FAILURE)

{

RETURN_NULL();

}

php_printf(“a + b = %d”, a + b);

}

Here zend_parse_paremeters() function take care of the values passed. If the values aren’t successfully passed the function will return null. Otherwise print sum.

However passing sting as parameter will take a bit more core then passing integer and float values.

The function for accepting sting as parameter will look like as

PHP_FUNCTION(handle_string)

{

char *name;

long name_len;

if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, “sl”, &name, &name_len) == FAILURE)

{

RETURN_NULL();

}

PHPWRITE(name, name_len);

}

Methods can accept optional parameters. Like

void printme(char[] name, int len = 9)

{

}

While call this method, you must pass array of characters. This method can accept an optional parameter len.

If len is not provided, it is set to 9.

To define a function accepting optional parameters while building extension, you will need to write the following code.

PHP_FUNCTION(prinntme)

{

zval *arr;

long num;

if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, “a|l”,&arr, &num) == FAILURE)

{

RETURN_NULL();

}

// code goes here

}

Here “a|l” define that the first argument is compulsory while the second parameters is optional.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: