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 |
好了类可以使用了!