PHP Extensions: returning values

10 May

When it comes to functions and methods, its important that they return value(s);

Method have return statement which is executed at the end. The code that is placed after the return statement may never execute.

While building extension, you can write return statement to return value from the method. One important thing zend provide is return_value, that is available when a function is called.

In c if you want to return 42. it will be as simple as this

return 42;

However zend provided different approaches to achieve this.

This can be achieved as

PHP_FUNCTION(return_value)

{

zval *val;

MAKE_STD_ZVAL(val);

ZVAL_LONG(val, 42);

return val;

}

Another very simple approach may be

PHP_FUNCTION(return_value)

{

ZVAL_LONG(return_value, 42);

return;

}

Or

PHP_FUNCTION(return_value)

{

Z_TYPE_P(return_value) = IS_LONG;

Z_LVAL_P(return_value) = 42;

return;

}

Or

PHP_FUNCTION(return_value)

{

return_value->type = IS_LONG;

return_value->value.lval = 42;

return;

}

However this isn’t good approach to be used. You can use another approach as

PHP_FUNCTION(return_value)

{

RETVAL_LONG(42);

Return;

}

One Response to “PHP Extensions: returning values”

  1. alasondro July 1, 2009 at 12:15 am #

    Nice post! But what if i want to return an unsigned long for example? How would i do that?

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: