搜尋
首頁後端開發php教程详解WordPress中用于合成数组的wp_parse_args()函数_php技巧

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函数用是将两个或多个数组的单元合并起来,一个数组中的值附加在前一个数组的后面。返回作为结果的数组。

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何使PHP應用程序更快如何使PHP應用程序更快May 12, 2025 am 12:12 AM

tomakephpapplicationsfaster,關注台詞:1)useopcodeCachingLikeLikeLikeLikeLikePachetoStorePreciledScompiledScriptbyTecode.2)MinimimiedAtabaseSqueriSegrieSqueriSegeriSybysequeryCachingandeffeftExting.3)Leveragephp7 leveragephp7 leveragephp7 leveragephpphp7功能forbettercodeefficy.4)

PHP性能優化清單:立即提高速度PHP性能優化清單:立即提高速度May 12, 2025 am 12:07 AM

到ImprovephPapplicationspeed,關注台詞:1)啟用opcodeCachingwithapCutoredUcescriptexecutiontime.2)實現databasequerycachingingusingpdotominiminimizedatabasehits.3)usehttp/2tomultiplexrequlexrequestsandreduceconnection.4 limitesclection.4.4

PHP依賴注入:提高代碼可檢驗性PHP依賴注入:提高代碼可檢驗性May 12, 2025 am 12:03 AM

依赖注入(DI)通过显式传递依赖关系,显著提升了PHP代码的可测试性。1)DI解耦类与具体实现,使测试和维护更灵活。2)三种类型中,构造函数注入明确表达依赖,保持状态一致。3)使用DI容器管理复杂依赖,提升代码质量和开发效率。

PHP性能優化:數據庫查詢優化PHP性能優化:數據庫查詢優化May 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

簡單指南:帶有PHP腳本的電子郵件發送簡單指南:帶有PHP腳本的電子郵件發送May 12, 2025 am 12:02 AM

phpisusedforsenderemailsduetoitsbuilt-inmail()函數andsupportivelibrariesLikePhpMailerAndSwiftMailer.1)usethemail()functionForbasiceMails,butithasimails.2)butithasimail.2)

PHP性能:識別和修復瓶頸PHP性能:識別和修復瓶頸May 11, 2025 am 12:13 AM

PHP性能瓶颈可以通过以下步骤解决:1)使用Xdebug或Blackfire进行性能分析,找出问题所在;2)优化数据库查询并使用缓存,如APCu;3)使用array_filter等高效函数优化数组操作;4)配置OPcache进行字节码缓存;5)优化前端,如减少HTTP请求和优化图片;6)持续监控和优化性能。通过这些方法,可以显著提升PHP应用的性能。

PHP中的依賴注入:一個簡單的解釋PHP中的依賴注入:一個簡單的解釋May 10, 2025 am 12:08 AM

依賴性(di)inphpenhancesCodeFlexibility andTestability by decouplingClassesscyclasses fromtheippentencies.1)UseConstructorientoctionTopAssDopassDectiesViactructors Viactructors

PHP DI容器比較:選擇哪一個?PHP DI容器比較:選擇哪一個?May 10, 2025 am 12:07 AM

推薦Pimple用於簡單項目,Symfony的DependencyInjection用於復雜項目。 1)Pimple適合小型項目,因其簡單和靈活。 2)Symfony的DependencyInjection適合大型項目,因其功能強大。選擇時需考慮項目規模、性能需求和學習曲線。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境