这是一篇学习摘记。以下面的PHP类为例:

class shipping
{
    private _x;

    public function setx($x) {
      $this->_x = $x;
    }

    public function getx() {
       return $this->_x;
    }
}

下面是C扩展创建步骤

1 在头文件声明方法

PHP_METHOD(shipping, setx);
PHP_METHOD(shipping, getx);

2 创建function_entry

//申明方法
ZEND_BEGIN_ARG_INFO(setx_arg, 1)
ZEND_ARG_INFO(0,x)
ZEND_END_ARG_INFO()

const zend_function_entry shipping_functions[] = {
	PHP_FE(confirm_shipping_compiled,	NULL)		/* For testing, remove later. */
	PHP_ME(shipping, getx, setx_arg, ZEND_ACC_PUBLIC)
	PHP_ME(shipping, setx, NULL, ZEND_ACC_PUBLIC)
	PHP_FE_END	/* Must be the last line in shipping_functions[] */
};

3 注册类

zend_class_entry *shipping_ce;
PHP_MINIT_FUNCTION(shipping)
{
	/* If you have INI entries, uncomment these lines
	REGISTER_INI_ENTRIES();
	*/
	zend_class_entry shipping;

	INIT_CLASS(shipping, "shipping", shipping_functions);
	shipping_ce = zend_register_internal_class_ex(&shipping, NULL, NULL TSRMLS_CC);
	zend_declare_property_null(shipping_ce, ZEND_STRL("_x"), ZEND_ACC_PRIVATE TSRMLS_CC);//初始化_x属性
	return SUCCESS;
}

4 创建实现类的方法

PHP_METHOD(shipping, getx)
{
	long int x;
	if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &x) == FAILURE) {
		RETURN_FALSE;
	}
	zend_update_property_long(Z_OBJECT_P(getThis()), getThis(), ZEND_STRL("_x"), x TSRMLS_CC);
	RETURN_TRUE;
}


PHP_METHOD(shipping, setx)
{
	zval *p;
	long int i;
	p = zend_read_property(Z_OBJECT_P(getThis()), getThis(), ZEND_STRL("_x"), 0 TSRMLS_CC);
	i = Z_LVAL_P(p);
	RETURN_LONG(i);
}

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注