Current Location: Home> Latest Articles> Comprehensive Guide to PHP7 Extension Development: Parameters and Return Values

Comprehensive Guide to PHP7 Extension Development: Parameters and Return Values

gitbox 2025-07-31

Overview of PHP7 Extension Development

PHP extensions are dynamic libraries written in C to extend the core functionality of PHP. By writing custom extensions, developers can add new functions, classes, and data structures to PHP. Compared to previous versions, PHP7 introduces numerous optimizations in extension architecture, offering significant performance improvements and a cleaner syntax.

Parameter Passing in PHP7 Extensions

When developing extensions in PHP7, parameter handling is a crucial component. There are two primary methods of passing parameters: by value and by reference. The following examples demonstrate how each method works.

Passing by Value

In value passing, changes made to the parameter within the function do not affect the original variable. This is suitable for read-only use cases.


PHP_FUNCTION(my_function) {
    int arg1;
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &arg1) == FAILURE) {
        return;
    }
    // Modify the parameter value
    arg1 = arg1 * 2;
    RETURN_LONG(arg1);
}

In the example above, the zend_parse_parameters function is used to parse an integer argument, double its value, and return it using RETURN_LONG.

Passing by Reference

Unlike passing by value, reference passing allows direct manipulation of the original variable by working on its memory address.


PHP_FUNCTION(my_function) {
    int arg1;
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &arg1) == FAILURE) {
        return;
    }
    // Modify the parameter value
    arg1 = arg1 * 2;
    RETURN_LONG(arg1);
}

Though the syntax looks similar to value passing, the internal handling allows modifying the original data directly.

Handling Return Values in PHP7 Extensions

Returning values is another key aspect of extension development. PHP7 provides several macros to efficiently handle this.

Returning a String

To return a string from an extension function, you can use the RETURN_STRING macro.


PHP_FUNCTION(my_function) {
    RETURN_STRING("Hello, world", 1);
}

The second parameter, 1, indicates that PHP should allocate and copy the string internally.

Returning an Integer

Returning an integer is straightforward using the RETURN_LONG macro.


PHP_FUNCTION(my_function) {
    RETURN_LONG(42);
}

This macro directly returns the integer to the PHP script that calls the extension function.

Conclusion

This article covered how to handle parameters and return values in PHP7 extension development, including passing by value and reference, and returning strings and integers. Mastering these core techniques enables developers to write efficient and robust PHP extensions that fully leverage the performance of C.