Home >Backend Development >PHP Tutorial >Writing parameter type bindings for PHP extension functions
Let’s take a look at how to implement type binding through it, but this feature can only be used in Zend Engine 2, which is PHP5. Let's review ZE2's argument info structure again. The declaration of each arg info structure starts with the ZEND_BEGIN_ARG_INFO() or ZEND_BEGIN_ARG_INFO_EX() macro function, followed by several lines of ZEND_ARG_*INFO() macro function, and finally ends with the ZEND_END_ARG_INFO() macro function. If we want to rewrite the count() function in PHP language, we can:
ZEND_FUNCTION(sample_count_array)
{
zval *arr;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a",&arr) == FAILURE)
{
using using using RETURN_LONG(zend_hash_num_elements(Z_ARRVAL_P(arr)));
}
zend_parse_parameters() itself can guarantee that the parameter passed is an array. But if we receive parameters through the zend_get_parameter() function, we are not so lucky, and we need to perform type checking ourselves. If you want the kernel to automatically complete type verification, you need arg_info:
ZEND_BEGIN_ARG_INFO(php_sample_array_arginfo, 0)
ZEND_ARG_ARRAY_INFO(0, arr, 0)
ZEND_END_ARG_INFO()
....
PHP_FE(sample_count_array, php_sample_array_arginfo)
. ...
In this way, we have handed over the type proofreading work to Zend Engine. Don’t you feel a sense of relief! You've also given your argument a name so that the generated error messages can be more meaningful to script writers attempting to use your API. We can also verify the object in the argument and restrict it to inherit from a certain class or implementation a certain interface and so on.
ZEND_BEGIN_ARG_INFO(php_sample_class_arginfo, 0)
ZEND_ARG_OBJ_INFO(1, obj, stdClass, 0)
ZEND_END_ARG_INFO()
It should be noted that the value of the first parameter at this time is the number 1, which means it is passed by reference. In fact, this parameter is almost useless for objects, because all objects in ZE2 are passed by reference by default when used as function parameters. But we must set this parameter to the number 1, unless you don't want your extension to be compatible with PHP4. In PHP4, objects are passed as a complete copy, not by reference.