PHP擴展學習:編寫一個類
php擴展開發肯定要學會如何編寫一個類,因爲現在都是OOP的開發思想,同時也是爲了使用的方便:
同樣使用之前編寫的只有一個函數的擴展myext:
裏面就是一個類 myclass:實現的功能如下:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
|
class
myclass{ private
$name ; CONST BYE= "\nbye bye" ; CONST WEL= "welcome\n" ; public
function __construct(){ echo
self::WEL; } public
function setName( $name ){ $this ->name= $name ; } public
function getName(){ return
$this ->name; } public
function __destruct(){ echo
self::BYE; } } |
在php_myext.h 中聲明:
1
2
3
4
|
ZEND_METHOD(myclass,__construct); ZEND_METHOD(myclass,setName); ZEND_METHOD(myclass,getName); ZEND_METHOD(myclass,__destruct); |
方法的具體實現:
1、註冊類:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
|
PHP_MINIT_FUNCTION(myext) { /* If you have INI entries, uncomment these lines REGISTER_INI_ENTRIES(); */ //註冊類 zend_class_entry ce; INIT_CLASS_ENTRY(ce, "myclass" ,myclass_method); myclass_ce=zend_register_internal_class(&ce TSRMLS_CC); //定義屬性 zend_declare_class_constant_stringl(myclass_ce,ZEND_STRL( "WEL" ),ZEND_STRL( "welcome\n" )
TSRMLS_CC); zend_declare_class_constant_stringl(myclass_ce,ZEND_STRL( "BYE" ),ZEND_STRL( "\nbye
bye" ) TSRMLS_CC); zend_declare_property_null(myclass_ce,ZEND_STRL( "name" ),ZEND_ACC_PRIVATE TSRMLS_CC); return
SUCCESS; } |
2、註冊方法
1
2
3
4
5
6
7
|
const
zend_function_entry myclass_method[]={ ZEND_ME(myclass,__construct,NULL,ZEND_ACC_PUBLIC|ZEND_ACC_CTOR) ZEND_ME(myclass,setName,NULL,ZEND_ACC_PUBLIC) ZEND_ME(myclass,getName,NULL,ZEND_ACC_PUBLIC) ZEND_ME(myclass,__destruct,NULL,ZEND_ACC_PUBLIC|ZEND_ACC_DTOR) PHP_FE_END }; |
3、定義方法
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
/* {{{ proto myclass::__construct() */ ZEND_METHOD(myclass,__construct){ zval **wel; zend_class_entry *ce; ce=Z_OBJCE_P(getThis()); zend_hash_find(&ce->constants_table,ZEND_STRS( "WEL" ), ( void
**)&wel); php_printf( "%s" ,Z_STRVAL_PP(wel)); } /* }}} */ /* {{{ proto myclass::setName() */ ZEND_METHOD(myclass,setName){ zend_class_entry *ce; ce=Z_OBJCE_P(getThis()); char
*name; int
name_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC,
"s" , &name, &name_len) == FAILURE){ WRONG_PARAM_COUNT; } zend_update_property_stringl(ce,getThis(),ZEND_STRL( "name" ),name,name_len TSRMLS_CC); RETURN_TRUE; } /* }}} */ /* {{{ proto myclass::getName() */ ZEND_METHOD(myclass,getName){ zval *name; char
*str; zend_class_entry *ce; ce=Z_OBJCE_P(getThis()); name=zend_read_property(ce,getThis(),ZEND_STRL( "name" ),0 TSRMLS_CC);
str=Z_STRVAL_P(name); RETURN_STRINGL(str,Z_STRLEN_P(name),1); } /* }}} */ /* {{{ proto myclass::__destruct() */ ZEND_METHOD(myclass,__destruct){ zval **bye; zend_class_entry *ce; ce=Z_OBJCE_P(getThis()); zend_hash_find(&ce->constants_table,ZEND_STRS( "BYE" ),( void
**)&bye); php_printf( "%s" ,Z_STRVAL_PP(bye)); } /* }}} */ |
1
2
3
|
phpize . /configure make
&& make install |
好了類可以使用了!