使用PHP可以对字符串进行压缩,但不涉及任何压缩文件。
下面的例子,使用 gzcompress() 和 gzuncompress() 函数:
$string =
"Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Nunc ut elit id mi ultricies
adipiscing. Nulla facilisi. Praesent pulvinar,
sapien vel feugiat vestibulum, nulla dui pretium orci,
non ultricies elit lacus quis ante. Lorem ipsum dolor
sit amet, consectetur adipiscing elit. Aliquam
pretium ullamcorper urna quis iaculis. Etiam ac massa
sed turpis tempor luctus. Curabitur sed nibh eu elit
mollis congue. Praesent ipsum diam, consectetur vitae
ornare a, aliquam a nunc. In id magna pellentesque
tellus posuere adipiscing. Sed non mi metus, at lacinia
augue. Sed magna nisi, ornare in mollis in, mollis
sed nunc. Etiam at justo in leo congue mollis.
Nullam in neque eget metus hendrerit scelerisque
eu non enim. Ut malesuada lacus eu nulla bibendum
id euismod urna sodales. ";
$compressed = gzcompress($string);
echo "Original size: ". strlen($string)."\n";
/* prints
Original size: 800
*/
echo "Compressed size: ". strlen($compressed)."\n";
/* prints
Compressed size: 418
*/
// getting it back
$original = gzuncompress($compressed);
压缩率可以达到 50% 左右。
另外,函数 gzencode() 和 gzdecode() 也可以达到类似结果,只是通过使用不同的压缩算法实现而已。
php中有一个函数叫做 register_shutdown_function(),可以让你在某段脚本完成运行之前,执行一些指定代码。
假设你需要在脚本执行结束前捕获一些基准统计信息,例如运行的时间长度:
// capture the start time
$start_time = microtime(true);
// do some stuff
// ...
// display how long the script took
echo "execution took: ".
(microtime(true) - $start_time).
" seconds.";
这似乎微不足道,你只需要在脚本运行的最后添加相关代码。但是如果你调用过 exit() 函数,该代码将无法运行。
此外,如果有一个致命的错误,或者脚本被用户意外终止,它可能无法再次运行。
当你使用 register_shutdown_function() 函数,代码将继续执行,不论脚本是否停止运行:
$start_time = microtime(true);
register_shutdown_function('my_shutdown');
// do some stuff
// ...
function my_shutdown() {
global $start_time;
echo "execution took: ".
(microtime(true) - $start_time).
" seconds.";
}
PHP 允许定义可选参数的函数,也完全允许任意数目的函数参数的方法。
可选参数的例子:
// function with 2 optional arguments
function foo($arg1 = '', $arg2 = '') {
echo "arg1: $arg1\n";
echo "arg2: $arg2\n";
}
foo('hello','world');
/* prints:
arg1: hello
arg2: world
*/
foo();
/* prints:
arg1:
arg2:
*/
如何建立能够接受任何参数数目的函数。
需要使用 func_get_args() 函数:
// yes, the argument list can be empty
function foo() {
// returns an array of all passed arguments
$args = func_get_args();
foreach ($args as $k => $v) {
echo "arg".($k+1).": $v\n";
}
}
foo();
/* prints nothing */
foo('hello');
/* prints
arg1: hello
*/
foo('hello', 'world', 'again');
/* prints
arg1: hello
arg2: world
arg3: again
*/