在日常的调试中,我们经常需要输出数组,但是print_r函数输出的数组是没有格式的,不太好看,
为了方便,我们只要自己增加一个函数,如
function dump($arr) {
echo '< pre>';
print_r($arr);
echo '< /pre>';
}
例如thinkphp就是这么做的,但是个人感觉太麻烦了,
如果php有个类似的内置函数,那不是方便多了?为此我们可以更改print_r
的源代码,让他在输出数组前先输出pre标签,print_r的源代码在ext/standard/basic_functions.c中,
但是呢,修改php的原有函数毕竟不太好,我们还是新添加一个扩展好了。
我们添加一个tiyee扩展,增加一个dump()函数
代码如下
cd /path/to/phpsource/ext
./ext_skel --extname=tiyee
cd tiyee
vi config.m4
出现如下提示
$ cd ..
$ vi ext/tiyee/config.m4
$ ./buildconf
$ ./configure --\[with|enable\]-tiyee
$ make
$ ./sapi/cli/php -f ext/tiyee/tiyee.php
$ vi ext/tiyee/tiyee.c
$ make
Repeat steps 3-6 until you are satisfied with ext/tiyee/config.m4 and step 6 confirms that your module is compiled into PHP. Then, start writing code and repeat the last two steps as often as necessary.
然后进入生成的文件夹,打开config.m4
cd tiyee
vi config.m4
然后,将里面的代码里面的16-18行前面的dnl注释去掉,即改成如下
PHP_ARG_ENABLE(tiyee, whether to enable tiyee support,
Make sure that the comment is aligned:
[ --enable-tiyee Enable tiyee support])
然后运行
phpize
生成如下提示
Configuring for:
PHP Api Version: 20121113
Zend Module Api No: 20121212
Zend Extension Api No: 220121212
打开php_tiyee.h
,在PHP_FUNCTION(confirm_tiyee_compiled); /* For testing, remove later. */
下面增加一行(你其实也可以直接更改它)
PHP_FUNCTION(confirm_tiyee_compiled); /* For testing, remove later. */
PHP_FUNCTION(dump);
然后打开tiyee.c
,在PHP_FE(confirm_tiyee_compiled, NULL) /* For testing, remove later. */
下面增加一行
改成
PHP_FE(confirm_tiyee_compiled, NULL) /* For testing, remove later. */
PHP_FE(dump, NULL)
然后下面增加具体的函数,可以在
PHP_FUNCTION(confirm_tiyee_compiled)
{
char *arg = NULL;
int arg_len, len;
char *strg;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &arg, &arg_len) == FAILURE) {
return;
}
len = spprintf(&strg, 0, "Congratulations! You have successfully modified ext/%.78s/config.m4. Module %.78s is now compiled into PHP.", "jumtao", arg);
RETURN_STRINGL(strg, len, 0);
}
增加一行,变成
PHP_FUNCTION(dump)
{
zval *var;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &var) == FAILURE) {
RETURN_FALSE;
}
printf("< pre >\n");
zend_print_zval_r(var, 0 TSRMLS\_CC);
printf("< /pre > \n");
}
PHP_FUNCTION(confirm_tiyee_compiled)
{
char *arg = NULL;
int arg_len, len;
char *strg;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &arg, &arg_len) == FAILURE) {
return;
}
len = spprintf(&strg, 0, "Congratulations! You have successfully modified ext/%.78s/config.m4. Module %.78s is now compiled into PHP.", "jumtao", arg);
RETURN_STRINGL(strg, len, 0);
}
现在我们可以编译了
./configure --with-php-config=/usr/local/php/bin/php-config /*后面的php-config地址按你的实际地址写*/
make
make install
然后再php.ini里添加
extension=tiyee.so
然后重启php-fpm
试试,这时试试,是不是可以了!