PHP内核探索:定义接口
PHP内核    2019-04-25 16:30:38    14    0    0
admin   PHP内核

定义一个接口还是很方便的,我先给出一个PHP语言中的形式。

1<?php
2interface i_myinterface
3{
4    public function hello();
5}
6?>

那它在扩展中的实现是这样的。

01zend_class_entry *i_myinterface_ce;
02 
03static zend_function_entry i_myinterface_method[]={
04    ZEND_ABSTRACT_ME(i_myinterface, hello, NULL) //注意这里的null指的是arginfo
05    {NULL,NULL,NULL}
06};
07 
08ZEND_MINIT_FUNCTION(test)
09{  
10    zend_class_entry ce;
11    INIT_CLASS_ENTRY(ce, "i_myinterface", i_myinterface_method);
12 
13    i_myinterface_ce = zend_register_internal_interface(&ce TSRMLS_CC);
14    return SUCCESS;
15}

我们使用ZEND_ABSTRACT_ME()宏函数来为这个接口添加函数,它的作用是声明一个类似虚函数的东西,不用实现。也就是说我们不用为其添加ZEND_METHOD(i_myinterface,hello){...}的实现。但是这个宏函数只能为我们实现public类型的函数声明,如果有其它特殊需要,需要使用ZEND_FENTRY()宏函数来实现,因为ZEND_ABSTRACT_ME也不过是后者的一种封装。

下面我们在PHP语言中使用这个接口。

01<?php
02class sample implements i_myinterface
03{
04    public $name "hello world!";
05     
06    public function hello()
07    {
08        echo $this->name."\n";
09    }
10}
11 
12$obj new sample();
13$obj->hello();
14?>

上一篇: PHP内核探索:继承与实现接口

下一篇: PHP内核探索:命名空间

14
登录 后评论.
没有帐号? 现在注册.
0 评论
Table of content