首頁  >  文章  >  後端開發  >  php7擴充類別的寫法是什麼

php7擴充類別的寫法是什麼

醉折花枝作酒筹
醉折花枝作酒筹轉載
2021-06-30 09:16:372441瀏覽

在php7中,有許許多多的擴充類,今天我們就以person類為例實作doing方法和saying方法,有需要的小夥伴可以參考一下。

php7擴充類別的寫法是什麼

1.需要實作的細節

實作一個person類別

實作一個doing方法和saying方法

2.第一個擴充

2.1建立類別的擴充:

[root@bogon ext]# cd /usr/local/src/php-7.0.3/ext
[root@bogon ext]# ./ext_skel --extname=person

2.2 修改設定

[root@bogon ext]# vim person/config.m4
dnl PHPARGWITH(person, for person support,
dnl Make sure that the comment is aligned:
dnl [ --with-person Include person support])

變更為:

PHPARGWITH(person, for person support,
dnl Make sure that the comment is aligned:
[ --with-person Include person support])

2.3 實作程式碼

在php_person.h頭中加上

extern zend_class_entry *person_ce;
PHP_METHOD(person_ce,__construct);
PHP_METHOD(person_ce,saying);
PHP_METHOD(person_ce,doing);

在person.c頭中加上

/** * 声明构造函数 * 
@param * @return */
ZEND_METHOD(person,__construct){        
zval *pThis;        
pThis = getThis();    
zend_printf("construct\n");
}
/** * 声明析造函数 *
 @param * @return */
ZEND_METHOD(person,__destruct){    
zend_printf("destruct\n");
}
ZEND_METHOD(person,doing){    
zend_printf("doing\n");
}
ZEND_METHOD(person,saying){    
zend_printf("saying\n");
}
//这个函数需要加上声明,去掉了没用的test函数const zend_function_entry person_functions[] = {    
ZEND_ME(person, __construct, global_config_arg, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)    
ZEND_ME(person,doing,NULL,ZEND_ACC_PUBLIC) ZEND_ME(person,saying,NULL,ZEND_ACC_PUBLIC)    
ZEND_ME(person,__destruct,NULL,ZEND_ACC_PUBLIC|ZEND_ACC_DTOR)    
PHP_FE_END  
/* Must be the last line in person_functions[] */
};
//将类和方法注册到zendPHP_MINIT_FUNCTION(person){       
zend_class_entry ce;       
INIT_CLASS_ENTRY(ce, "person", person_functions);       
person_ce = zend_register_internal_class(&ce TSRMLS_CC);       
zend_declare_property_null(person_ce,"saying",strlen("saying"),ZEND_ACC_PUBLIC);       
zend_declare_property_null(person_ce,"doing",strlen("doing"),ZEND_ACC_PUBLIC);    
return SUCCESS;
}

2.4 編譯

* [root@bogon hello]# [root@localhost person]# ./configure && make && make install

2.5 擴充安裝

 改更php.ini 加上

[person] extenstion=person.so

2.6 擴充使用

[root@bogon tests]# cat test.php
<?php
$n = new person();
echo $n->saying();
echo $n->doing();
[root@localhost tests]# php test.phpconstructsayingdoingdestruct

推薦學習:php影片教學

#

以上是php7擴充類別的寫法是什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:imooc.com。如有侵權,請聯絡admin@php.cn刪除