`
dcj3sjt126com
  • 浏览: 1825432 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

写第一个PHP扩展, 实现计算数组的个数

    博客分类:
  • PHP
阅读更多

需求: 写第一个PHP扩展, 里面包含一个函数叫 maxwelldu, maxwelldu可以计算数组的长度(与count相同)

要求: 了解C/C++编程, 熟悉PHP编程

系统: CentOS6.5

环境: LNMP(yum方式安装)

 

踏出第一步开始写PHP扩展, 将借助一个工具, 而这个工具在PHP的源码里面, 所以我们下载一个PHP的源码, http://php.net/downloads.php

cd ~
mkdir software
cd software
wget http://cn2.php.net/distributions/php-5.6.11.tar.gz
tar zxvf php-5.6.11.tar.gz
cd php-5.6.11/ext

 #创建扩展项目, 创建完成之后ext目录下会多一个sayhello的文件夹,这个文件夹就是我们的扩展项目

./ext_skel --extname=maxwelldu
cd maxwelldu
vim config.m4

 #打开允许, 去掉PHP_ARG_ENABLE这一行前的dnl和 [ --enable-maxwelldu ] 这一行前面的dnl

PHP_ARG_ENABLE(maxwelldu, whether to enable maxwelldu support,
dnl Make sure that the comment is aligned:
[  --enable-maxwelldu           Enable maxwelldu support])

 #文件末尾添加

vim php_maxwelldu.h

PHP_FUNCTION(maxwelldu);

 #在文件末尾添加

vim maxwelldu.c
```
PHP_FUNCTION(maxwelldu){
        zval *arr;               //声明一个变量来接受数组参数
        HashTable *arr_hash;    //声明一个HashTable的变量
        int array_count;        //声明一个数组长度的变量
        if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &arr)==FAILURE){ //判断接受的数组是>否是数组, 并把值放入arr中
                return;
        }
        arr_hash = Z_ARRVAL_P(arr); //将数组转换成HashTable
        array_count = zend_hash_num_elements(arr_hash);//通过zend提供的函数获取一共有多少个元素
        RETURN_LONG(array_count); //返回元素的个数
}
```

#然后修改zend_function_entry maxwelldu_functions[] = { 的内容如下
```
const zend_function_entry maxwelldu_functions[] = {
        PHP_FE(maxwelldu,NULL)
        {NULL,NULL,NULL}
};
```

 #编译

#注意PHP的安装方式不同php-config的目录也可能不一样

phpize
./configure --with-php-config=/usr/bin/php-config
make
make test
make install

 #这个时候会自动将扩展放到对应的扩展目录

#修改php的配置文件, 像平时添加mysql,memcache等扩展一样

#重启apache或者php-fpm

extension=maxwelldu.so
service httpd restart
service php-fpm restart

 #查看已经安装的扩展

php -m

#在phpinfo里面可以查看到maxwelldu

#然后就可以在PHP脚本里面使用了

<?php
$arr = [
	1, 2, 3, 4, 5
];
echo maxwelldu($arr) == count($arr), PHP_EOL; //打印出1就表示函数返回的数组个数和系统的count函数返回值一样

  

参考地址:

https://github.com/walu/phpbook

http://blog.csdn.net/heiyeshuwu/article/details/3453854

http://www.360doc.com/content/13/1226/17/14452132_340319333.shtml

http://www.nowamagic.net/librarys/veda/detail/1467

http://blog.csdn.net/super_ufo/article/details/3863731

http://www.phppan.com/2010/02/php-source-12-return_value/

http://www.ccvita.com/496.html

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics