163

PHP-X 系列教程:内置函数的使用 - 个人文章 - SegmentFault

 6 years ago
source link: https://segmentfault.com/a/1190000011568918?
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

本文主要介绍PHP-X内置函数的使用,在PHP扩展开发中,会经常用到这些内置函数,PHP-X的封装,使得调用这些函数像PHP代码一样简单。

在扩展中需要输出一些内容,可以使用echo函数。echo的使用方法与C语言的printf是完全一致的。具体请参考printf相关文章。

  • 在命令行环境(cli),echo会打印屏幕
  • php-fpmapache中,echo会输出内容到浏览器客户端
PHPX_FUNCTION(cpp_test)
{
    echo("a=%d, b=%f, c=%s.\n", args[0].toInt(), args[1].toFloat(), args[2].toCString());
}

var_dump

开发调试PHP程序时,经常需要打印一些变量的值。PHP提供了var_dump函数来打印变量。在PHP-X中也可以使用var_dump,这个函数接受一个Variant对象。

PHPX_FUNCTION(cpp_test)
{
    var_dump(args[0]);
}

include

包含PHP文件。注意文件不存在会抛出致命错误。正确加载后,此PHP文件中的代码将被执行。可以使用include在扩展中引入PHP代码实现的类和函数。

PHPX_FUNCTION(cpp_test)
{
    include("/data/php/library/Autoloader.php");
}

error

打印PHP错误日志,相当于PHPtrigger_error函数。此函数与echo很相似,唯一不同的插入了第一个参数,来接受错误等级,如E_ERRORE_WARNING

PHPX_FUNCTION(cpp_test)
{
    error(E_ERROR, "error: a=%d, b=%f, c=%s.\n", args[0].toInt(), args[1].toFloat(), args[2].toCString());
}

constant

获取常量的值。此函数可以用于获取define定义的常量以及const定义的类常量。

PHPX_FUNCTION(cpp_test)
{
    auto a = constant("PHP_VERSION");
    auto b = constant("PDO::VERSION");
    var_dump(a);
    var_dump(b);
}

global

获取全局变量的值。包括PHP的超全局变量和其他PHP代码使用global关键词声明的全局变量。

PHPX_FUNCTION(cpp_test)
{
    //相当于 $_GET
    auto a = global("_GET");
    //相当于 global $config
    auto b = global("config");
    var_dump(a);
    var_dump(b);
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK