wp_parse_args() 函數是 WordPress 核心經常用到的函數,它的用途很多,但最主要用來給一個數組參數(args)綁定默認值。
因為 wp_parse_args() 函數返回的一定是一個數組,所以他會把傳入查詢字符串和對象(object)自動轉換成數組,給了使用者更加方便的條件,也增加了兼容性。
常見的 query_posts()、wp_list_comments() 和 get_terms() 函數都使用了 wp_parse_args() 函數來幫它給數組參數添加默認值。
用法
wp_parse_args( $args, $defaults );
參數
$args
(數組 | 字符串)(必須)查詢字符串、對象或者數組參數,用來綁定默認值。
默認值:None
查詢字符串:
type=post&posts_per_page=5&cat=1
數組:
array( 'type' => 'post', 'posts_per_page' => 5, 'cat' => '1' )
$defaults
(數組)(可選)數組參數的默認參數。
默認值:空字符串
例子
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 );
/*
array(2) {
["text"]=>
string(21) "測試另一種用法"
["type"]=>
string(9) "字符串"
}
*/
//對象(object)
class args_obj{
public $text = '測試另一種用法';
public $type = '對象(object)';
function func(){
//轉換成數組的時候對象裡邊的函數會被忽略
}
}
$obj = new args_obj;
var_dump( $obj );
/*
object(args_obj)#2175 (2) {
["text"]=>
string(21) "測試另一種用法"
["type"]=>
string(18) "對象(object)"
}
*/
wp_parse_args函數源代碼詳解
wp_parse_args 函數的源代碼比較簡單,
依附於PHP 內置函數get_object_vars、array_merge與WordPress的wp_parse_str函數來實現,
以下是該函數的源代碼:
/**
* Merge user defined arguments into defaults array.
*
* This function is used throughout WordPress to allow for both string or array
* to be merged into another array.
*
* @since 2.2.0
*
*第一個參數可以是 字符串、數組或對象(obj)
* @param string|array $args Value to merge with $defaults
*第二個參數為默認的預設值數組,必須是數組
* @param array $defaults Array that serves as the defaults.
*返回值將是一個數組
* @return array Merged user defined values with defaults.
*/
function wp_parse_args( $args, $defaults = '' ) {
if ( is_object( $args ) )
//將接收的對象(obj)轉換為數組
$r = get_object_vars( $args );
elseif ( is_array( $args ) )
//如果是數組則不轉換
$r =& $args;
else
//將接收的字符串轉換為數組
wp_parse_str( $args, $r );
if ( is_array( $defaults ) )
return array_merge( $defaults, $r );
return $r;
}
其中get_object_vars函數是用來返回由對象屬性組成的關聯數組。
array_merge函數用是將兩個或多個數組的單元合並起來,一個數組中的值附加在前一個數組的後面。返回作為結果的數組。