PHP扩展开发:hello word!

本文详细介绍如何在5分钟内快速编写并安装自己的第一个PHP扩展——helloword。从生成扩展代码框架,到修改配置、实现功能、编译扩展及最终在PHP中使用该扩展,每个步骤都配以清晰的命令行指令和代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于php开发人员来说,写php扩展好像是一个很高级的东西。其实只是我们没有去接触,或者工作中根本没用到,所以感觉很高级。下面的例子,就是让你用5分钟,来编写你人生的第一个php扩展-hello word!

我们先假设业务场景,是需要有这么一个扩展,提供一个叫helloword的函数,他的主要作用是返回一段字符。(这个业务场景实在太假,大家就这么看看吧)对应的PHP代码可能是这样:

1function helloword($str){
2 
3$result = 'helloword!'.$str
4 
5return $result;
6 
7}

第一步,生成代码 PHP为了扩展开发的方便,提供了一个类似代码生成器的工具ext_skel,具体可以参见说明。  首先我们创建一个文件helloword.skel,它的内容为

1string helloword(string str)

就是告诉ext_skel这个东西,我们要做的扩展里面有个函数叫helloword。然后执行

1cd MooENV/src/php-5.3.8/ext/
2 
3./ext_skel --extname=helloword --proto=helloword.skel
4 
5cd helloword/

这时候,helloword这个扩展的代码框架就已经出来了。

第二步,修改配置  然后修改config.m4文件将10、11、12三行最前面的dnl删除掉,就是将

1dnl PHP_ARG_WITH(helloword, for helloword support,
2 
3dnl Make sure that the comment is aligned:
4 
5dnl [  --with-helloword             Include helloword support])

修改为

1PHP_ARG_WITH(helloword, for helloword support,
2 
3Make sure that the comment is aligned:
4 
5 [  --with-helloword             Include helloword support])

第三步,实现功能  修改源码helloword.c文件  找到将helloword这个函数修改为

1PHP_FUNCTION(helloword) {
2 
3char *str = NULL;
4 
5int argc = ZEND_NUM_ARGS();
6 
7int str_len;
8 
9char *result;
10 
11if (zend_parse_parameters(argc TSRMLS_CC, "s", &str, &str_len) == FAILURE)         return;
12 
13str_len = spprintf(&result, 0, "helloword! %s", str);
14RETURN_STRINGL(result, str_len, 0);
15 
16}

第四步,编译扩展  保存后,开始编译

1/usr/local/php/bin/phpize
2./configure --with-php-config=/usr/local/php/bin/php-config
3make && make install

第五步,添加扩展  这时候,一切顺利的话,该扩展已经在modules/helloword.so这个位置了。下面就是将这个扩展加入到PHP中去,让我们PHP程序可以调用到。

1vim /usr/local/php/lib/php.ini

extension=/usr/local/php/ext/helloword.so #在php.ini文件最后增加这一行

#重启PHP服务

1service php-fpm restart

写一个简单的寂寞代码helloword.php,内容如下:

1<?php
2 
3helloword('这就是我的第一个php扩展,实在太简单了!');

结果:

RV`~OQG]KP0PH]VV2_}$T)2

 

文章发布在我的个人小站(拖鞋小站): http://www.39gs.com/archive/152.html   多多关照!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值