Zephir是一个开源的用于简化PHP扩展的建立和维护的语言。它使得不擅长C/C++的PHP开发人员也能写出PHP扩展。Zephir是Zend Engine/PHP/Intermediate缩写,读音为zephyr。php
Zephir在语法上跟PHP有不少类似之处,PHP开发人员能够很快上手,但也有不少地方上的不一样须要咱们去学习。下面是Zephir一些主要的特点:html
要使用Zephir和编译出一个PHP扩展,须要先安装如下的依赖:mysql
这里选择使用git
的方式获取源代码并进行安装:git
bash$ git clone https://github.com/phalcon/zephir $ cd zephir $ ./install-json $ ./install -c
若是已经安装了
json-c
,那么能够忽略./install-json
这一步。github
经过运行zephir命令验证下是否安装成功:web
bash$ zephir help _____ __ _ /__ / ___ ____ / /_ (_)____ / / / _ \/ __ \/ __ \/ / ___/ / /__/ __/ /_/ / / / / / / /____/\___/ .___/_/ /_/_/_/ /_/ Zephir version 0.7.1b Usage: command [options] Available commands: stubs Generates extension PHP stubs install Installs the extension (requires root password) fullclean Cleans the generated object files in compilation build Generate/Compile/Install a Zephir extension generate Generates C code from the Zephir code clean Cleans the generated object files in compilation builddev Generate/Compile/Install a Zephir extension in development mode compile Compile a Zephir extension version Shows the Zephir version api [--theme-path=/path][--output-directory=/path][--theme-options={json}|/path]Generates a HTML API help Displays this help init [namespace] Initializes a Zephir extension Options: -f([a-z0-9\-]+) Enables compiler optimizations -fno-([a-z0-9\-]+) Disables compiler optimizations -w([a-z0-9\-]+) Turns a warning on -W([a-z0-9\-]+) Turns a warning off
下面咱们使用Zephier来建立一个“hello world”扩展。sql
首先,咱们使用init
命令来初始化扩展的基本结构(假设咱们扩展的名称为“utils”):json
bash$ zephir init utils
成功运行后,咱们应该会获得以下的目录结构:api
bashutils/ ext/ utils/
ext
目录里放的是编译器须要用到的代码,不用理会,咱们的Zephir代码将放在跟扩展名同名的utils
里。安全
咱们在utils
目录下建立一个文件:greeting.zep
,并编写代码:
phpnamespace Utils; class Greeting { public static function say() { echo "hello world!"; } }
这里不深刻Zephir的语法,可是能够看到语法跟PHP很相似,上面的代码定义了一个类Greeting
和一个方法say()
。
Zephir的语法详情能够参考官方的文档:http://zephir-lang.com/language.html。
接下来,咱们回到utils
根目录下并运行build
命令编译出扩展:
bash$ zephir build Preparing for PHP compilation... Preparing configuration file... Compiling... Installing... Extension installed! Add extension=utils.so to your php.ini Don't forget to restart your web serverp
编译成功后,咱们在PHP配置文件里增长如下一行:
iniextension=utils.so
经过以下命令查看咱们的扩展是否正常加载:
bashphp -m [PHP Modules] ... memcached mysql mysqli mysqlnd openssl utils ...
若是看到咱们扩展的名字,则证实已成功加载。
而后咱们在PHP里调用say()
方法:
php<?php echo Utils\Greeting::say(), "\n";
正常的话会输出:hello world!
。至此咱们也完成了咱们的第一个扩展。