使用zephir调用php扩展库或内置函数库

使用zephir调用php扩展库或内置函数库

zephir官网
github库
zephir文档

zephir提供了一种可以使用高级语言写php扩展的方法。

安装方法在github的readme中和文档中介绍的很清晰。
本文主要分享一个简单的demo,使用zephir可以调用php内置函数库,可以调用php的其他扩展库,同时也可以调用用户用php语言写的php函数。

zephir示例代码:

namespace Utils;

class Greeting
{
    private username;
    private password;

    public function __construct(string! username, string! password)
    {
        let this->username = username;
        let this->password = password;
    }

    // 调用PHP扩展库
    public function sayHello(string! tableName)
    {
        var dbh;
        let dbh = new \PDO("mysql:host=127.0.0.1:3306;dbname=test;charset=utf8mb4",this->username, this->password);
        return dbh->query("select * from ".tableName)->fetchAll(\PDO::FETCH_ASSOC);
    }

    // 调用php内置函数
    public function testString(string str)
    {
        var len = strlen(str);
        echo len;
        echo "\n";
        echo substr(str,1);
    }

    // 调用用户建立的php函数
    public function testMyFunc(string funcName, string avrg)
    {
        if function_exists(funcName) {
            return {funcName}(avrg);
        }else{
            return "error";
        }
    }
}

php使用代码示例:


($name){ return 'hello:'.$name; } $a = new \Utils\Greeting('root','12345678'); $res = $a->sayHello('users'); var_dump($res); echo "------"; $a->testString('helloworld'); $ff = $a->testMyFunc('demo','zhangsan'); var_dump($ff);

phalcon是一个使用zephir开发的全堆栈php开发框架,在学习zephir的过程中,可以尝试读一下phalcon的源码,会有很大帮助。

cphalcon/phalcon

你可能感兴趣的:(php)