wp_parse_args() 函数是 WordPress 核心经常用到的函数,它的用途很多,但最主要用来给一个数组参数(args)绑定默认值。
因为 wp_parse_args() 函数返回的一定是一个数组,所以他会把传入查询字符串和对象(object)自动转换成数组,给了使用者更加方便的条件,也增加了兼容性。
常见的 query_posts()、wp_list_comments() 和 get_terms() 函数都使用了 wp_parse_args() 函数来帮它给数组参数添加默认值。
用法
? 1 wp_parse_args( $args, $defaults );参数
$args
(数组 | 字符串)(必须)查询字符串、对象或者数组参数,用来绑定默认值。
默认值:None
查询字符串:
? 1 type=post&posts_per_page=5&cat=1数组:
? 1 array( 'type' => 'post', 'posts_per_page' => 5, 'cat' => '1' )$defaults
(数组)(可选)数组参数的默认参数。
默认值:空字符串
例子
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 function explain_parse_args( $args = array() ){ //$args 的默认值 $defaults = array( 'before' => '<div class="box">', 'after' => '</div>', 'echo' => true, 'text' => 'wp_parse_args() 函数演示' ); //绑定默认值 $r = wp_parse_args( $args, $defaults ); $output = $r['before'] . $r['text'] . $r['after']; if( !$r['echo'] ) return $output; echo $output; } //没有参数 explain_parse_args();//打印:<div class="box">wp_parse_args() 函数演示</div> //字符串参数 $output = explain_parse_args( 'text=字符串参数&before=<div class="box-2">&echo=0' ); echo $output;//打印:<div class="box-2">字符串参数</div> //数组参数 explain_parse_args( array( 'text' => '数组参数', 'before' => '<div class="box-3">' ) );//打印:<div class="box-3">数组参数</div> 还有另一种不使用第二个 $defaults 参数的用法,就是帮你把一个查询字符串、对象或者数组的变量直接转换成通用的数组,避免判断类型。 //字符串 $array = wp_parse_args( 'text=测试另一种用法&type=字符串' ); var_dump( $array ); //对象(object) class args_obj{ public $text = '测试另一种用法'; public $type = '对象(object)'; function func(){ //转换成数组的时候对象里边的函数会被忽略 } } $obj = new args_obj; var_dump( $obj ); wp_parse_args函数源代码详解
wp_parse_args 函数的源代码比较简单,
依附于PHP 内置函数get_object_vars、array_merge与WordPress的wp_parse_str函数来实现,
以下是该函数的源代码:
其中get_object_vars函数是用来返回由对象属性组成的关联数组。
array_merge函数用是将两个或多个数组的单元合并起来,一个数组中的值附加在前一个数组的后面。返回作为结果的数组。