PHP那些不常用但很有用的功能(1)

你可能知道PHP允许你定义一个默认参数的函数。但你可能并不知道PHP还允许你定义一个完全任意的参数的函数

下面是一个示例向你展示了默认参数的函数:


// 两个默认参数的函数
function foo($arg1 = '', $arg2 = '') {
echo "arg1: $arg1\n";
echo "arg2: $arg2\n";
}

foo('hello','world');
/* 输出:
arg1: hello
arg2: world
*/

foo();
/* 输出:
arg1:
arg2:
*/


现在我们来看一看一个不定参数的函数,其使用到了?func_get_args()方法:


// 是的,形参列表为空
function foo() {
// 取得所有的传入参数的数组
$args = func_get_args();
foreach ($args as $k => $v) {
echo "arg".($k+1).": $v\n";
}

}

foo();
/* 什么也不会输出 */

foo('hello');
/* 输出
arg1: hello
*/

foo('hello', 'world', 'again');
/* 输出
arg1: hello
arg2: world
arg3: again
*/


( ! ) Warning: Missing argument 1 for cwppos_show_review(), called in /data/www/enjoyphp/wp-content/themes/flat/content-single.php on line 29 and defined in /data/www/enjoyphp/wp-content/plugins/wp-product-review/includes/legacy.php on line 18
Call Stack
#TimeMemoryFunctionLocation
10.0000355048{main}( ).../index.php:0
20.0001355336require( '/data/www/enjoyphp/wp-blog-header.php' ).../index.php:17
30.162710154928require_once( '/data/www/enjoyphp/wp-includes/template-loader.php' ).../wp-blog-header.php:19
40.164010226072include( '/data/www/enjoyphp/wp-content/themes/flat/single.php' ).../template-loader.php:74
50.250610789800get_template_part( ).../single.php:5
60.250610790320locate_template( ).../general-template.php:167
70.250610790416load_template( ).../template.php:643
80.250710790800require( '/data/www/enjoyphp/wp-content/themes/flat/content-single.php' ).../template.php:686
90.255910776024cwppos_show_review( ).../content-single.php:29

1 评论

发表评论

电子邮件地址不会被公开。 必填项已用*标注