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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Gekkoou/article/details/84073446

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






猜你喜欢

转载自blog.csdn.net/Gekkoou/article/details/84073446