IT技术博客大学习 共学习 共进步
全部 移动开发 后端 数据库 AI 算法 安全 DevOps 前端 设计 开发者

解读PHP开源项目中列表和hook方法:while(has_items()): thme_ite();和apply_filters

五四陈科学院 2010-02-09 08:55:53 累计浏览 3,000 次
本机暂存

wordpress,lilina等开源项目中,常常会看到一些莫名的代码,来无影去无踪,看上去很有意味,特地拿来分析分析,看看一般的作法。

part 1  列表 循环显示

先看代码:

<?php
$num = 0;
if(has_items()) {
while(has_items()): the_item();
}
?>

以上代码,出自某开源项目。。。

再进入the_item()函数内部,可以看到一个关键的函数:

* Returns the current item
*
* @since 1.0
*
* @return bool|stdClass False if item doesn’t exist, otherwise returns the specified item
*/
public function current_item() {
$this->previous_item = $this->current_item;
$this->current_item = ”;

$item = each($this->items);
$item = $item['value'];
if(!$item)
return false;

$this->current_item = $item;
$this->current_feed = $item->feed;

return $item;
}

这个关键的函数是each(),来看手册:

each

(PHP 3, PHP 4, PHP 5)

each -  返回数组中当前的键/值对并将数组指针向前移动一步

说明

array each ( array &array )

返回 array 数组中当前指针位置的键/值对并向前移动数组指针。键值对被返回为四个单元的数组,键名为 01keyvalue。单元 0key 包含有数组单元的键名,1value 包含有数据。

如果内部指针越过了数组的末端,则 each() 返回 FALSE

综合来看,其实就是一个做了一个游标一样的模型,利用each来操作一个数组或者相似的结构,每次在显示的时候,都有对数据数组的本身操作,而while里的has_item,只是作简单的判断有无而已。

part2 hook

第二种情况,是一个叫apply_filters的函数的实现。先看代码:

function the_item() {
global $lilina_items, $item;

$item = apply_filters(’the_item’, $lilina_items->current_item());
}

这是lilina里的一个函数,要看的是这个apply_filters方法,有一个简单的例子:

function example_hook($string, $arg1, $arg2)
{
//Do stuff
return $string;
}
$value = apply_filters(’example_hook’, ‘filter me’, ‘arg1′, ‘arg2′);

apply_filters里面最关键的一个函数:

call_user_func_array

(PHP 4 >= 4.0.4, PHP 5)

call_user_func_array -  Call a user function given with an array of parameters

Description

mixed call_user_func_array ( callback function, array param_arr )

Call a user defined function given by function, with the parameters in param_arr.

其实这些渐渐被遗忘的函数,在高手们的使用下,对项目化的开发很有优势,随手记之。

同分类推荐文章

  1. 等了十年的 Go 链式管道,终于来了:seq 让你像写 Scala 一样写 Go (2026-06-25 18:38:18)
  2. Go 实验特性详解 (2026-06-21 10:05:27)
  3. amd64 微架构级别对 Go 程序性能提升多少? (2026-06-21 09:38:49)

查看更多 后端 文章 →

建议继续学习

  1. 使用gettext来支持PHP的多语言 (累计阅读 39,268)
  2. WordPress插件开发 -- 在插件使用数据库存储数据 (累计阅读 29,164)
  3. Paypal接口详细代码(PHP版,非API接口) (累计阅读 19,408)
  4. 我的PHP,Python和Ruby之路 (累计阅读 13,146)
  5. include(“./file.php”)和include(“file.php”)区别 (累计阅读 12,789)
  6. 15个最好的免费开源电子商务平台 (累计阅读 12,541)
  7. Redis消息队列的若干实现方式 (累计阅读 12,088)
  8. 到底什么是MVC? (累计阅读 11,865)
  9. 整理了一份招PHP高级工程师的面试题 (累计阅读 11,708)
  10. Rolling cURL: PHP并发最佳实践 (累计阅读 11,487)