linux zephir 编写 php 扩展 (入门篇)

17 篇文章 0 订阅

Zephir是一种语言, 在语法上跟PHP有很多相似之处, 就算不擅长C/C++的PHP开发人员也可快速上手, 编写PHP扩展.
安装方法自行谷歌或百度.

初始化

执行命令 zephir init test, 成功运行后, 会得到如下的目录结构

test/
   ext/
   test/

ext 目录里放的是编译需要用到的代码, 可忽略, 接下来要写的Zephir代码文件要放在 test


编写代码

test目录下创建文件, 名为 hello.zep (文件名一般为类名), 编写代码

namespace Test;

/**
 * This is a sample class
 */
class Hello
{
    /**
     * This is a sample method
     */
    public function say()
    {
        echo "hello world!";
    }
}

这样就定义了一个 Hello 的类和 say 的方法了


编译

返回上一层 test 目录, 执行命令 zephir build

# zephir build     
Preparing for PHP compilation...
Preparing configuration file...
Compiling...
Installing...
Extension installed!
Add extension=test.so to your php.ini
Don't forget to restart your web serverp

编译成功后, 在 php.ini 配置文件里增加一行

extension=test.so

test/ext/modules 下可看到 test.so 文件, test/ext/test 下可看到编译前生成的 .c 文件

#ifdef HAVE_CONFIG_H
#include "../ext_config.h"
#endif

#include <php.h>
#include "../php_ext.h"
#include "../ext.h"

#include <Zend/zend_operators.h>
#include <Zend/zend_exceptions.h>
#include <Zend/zend_interfaces.h>

#include "kernel/main.h"

ZEPHIR_INIT_CLASS(Test_Hello) {
	ZEPHIR_REGISTER_CLASS(Test, Hello, test, hello, test_hello_method_entry, 0);
	return SUCCESS;
}

PHP_METHOD(Test_Hello, say) {
	php_printf("%s", "hello world!");
}

验证

执行代码 php -m

# php -m
[PHP Modules]
...
test
...

看到扩展名字, 证明已成功加载

写一个 php 文件

<?php
echo Test\Hello::say();

访问后输出 hello world! 代表扩展完成了~


参考

官方文档: https://docs.zephir-lang.com/en/
git: https://github.com/phalcon/zephir






  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值