我們自訂一個Exception類,php的程式碼:
<code><span><span>class</span><span>TestException</span><span>extends</span><span>Exception</span> {</span>}</code>
程式碼實作:
<code><span>#include "Zend/zend_exceptions.h"</span> zend_class_entry *test_exception_ce; PHP_MINIT_FUNCTION(test) { zend_class_entry tmp_ce; INIT_CLASS_ENTRY(tmp_ce, <span>"TestException"</span>, NULL); test_exception_ce = zend_register_internal_class_ex(&tmp_ce, zend_exception_get_default(TSRMLS_C), NULL TSRMLS_CC); <span>return</span> SUCCESS; }</code>
這裡面主要就是實作了一個沒有方法的自訂Exception類,並且繼承了Exception這個類別。採用了zend_register_internal_class_ex
這個帶有_ex 後綴的宏,這個巨集的第二個參數zend_exception_get_default
(注意頭檔)指定了父類,也可以透過類名的方式來指定父類,可以看zend_exister_interzendregister_inter
的定義
<code><span>/* If parent_ce is not NULL then it inherits from parent_ce * If parent_ce is NULL and parent_name isn't then it looks for the parent and inherits from it * If both parent_ce and parent_name are NULL it does a regular class registration * If parent_name is specified but not found NULL is returned */</span> ZEND_API zend_class_entry *zend_register_internal_class_ex(zend_class_entry *class_entry, zend_class_entry *parent_ce, <span>char</span> *parent_name TSRMLS_DC) <span>/* {{{ */</span> { zend_class_entry *register_class; <span>if</span> (!parent_ce && parent_name) { zend_class_entry **pce; <span>if</span> (zend_hash_find(CG(class_table), parent_name, <span>strlen</span>(parent_name)+<span>1</span>, (<span>void</span> **) &pce)==FAILURE) { <span>return</span> NULL; } <span>else</span> { parent_ce = *pce; } } register_class = zend_register_internal_class(class_entry TSRMLS_CC); <span>if</span> (parent_ce) { zend_do_inheritance(register_class, parent_ce TSRMLS_CC); } <span>return</span> register_class; } <span>/* }}} */</span></code>
這個方法裡面parent_name
傳進來的時候必須是小寫的,否則在尋找類別名稱(zend_hash_find
)的時候就會失敗回傳NULL,例如:zend_hash_find