php扩展实践之定义类

zend_class_entry *learn_ce;

ZEND_BEGIN_ARG_INFO_EX(arginfo_learn___construct, 0, 0, 1)
    ZEND_ARG_INFO(0, name)
ZEND_END_ARG_INFO()

// Learn::__construct 的实现
ZEND_METHOD(learn, __construct) {
    char *name = "tianzi", *methodName;
    zval *method, *callResult, *instance;
    int nameLen = strlen(name);
    // 带有默许值的传入参数
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &name, &nameLen) == FAILURE) {
        RETURN_NULL();
    }
    instance = getThis();
    // 更新类的属性
    zend_update_property_stringl(learn_ce, instance, ZEND_STRL("name"), ZEND_STRL(name) TSRMLS_DC);
}
// Learn::hi 的实现
ZEND_METHOD(learn, hi) {
    zval *instance = getThis();
    // 读取类的属性
    zval *name = zend_read_property(learn_ce, instance, ZEND_STRL("name"), 0 TSRMLS_CC);
    char *theName = estrndup(Z_STRVAL_P(name), Z_STRLEN_P(name));
    php_printf("hi %s
", theName);
    efree(theName);
}
// 类方法的属性
static zend_function_entry learn_methods[] = {
    ZEND_ME(learn, __construct, arginfo_learn___construct, ZEND_ACC_PUBLIC | ZEND_ACC_CTOR)
    ZEND_ME(learn, hi, NULL, ZEND_ACC_PUBLIC)
    {NULL, NULL, NULL}
};

PHP_MINIT_FUNCTION(learn)
{
    zend_class_entry ce;
    INIT_CLASS_ENTRY(ce, "Learn", learn_methods);
    // 注册类
    learn_ce = zend_register_internal_class(&ce TSRMLS_CC);
    // 定义类属性
    zend_declare_property_null(learn_ce, ZEND_STRL("name"), ZEND_ACC_PUBLIC TSRMLS_CC);

    return SUCCESS;
}