您的位置:首页 > 编程语言 > PHP开发

回调、匿名函数、闭包在PHP中的应用

2013-12-17 22:06 731 查看
回调、匿名函数、闭包,这三个东东,由于平常基本用不到,所以对这三个知识点也不是很清楚。下面我把学习时,用到的例子记录到这里,方便日后查阅,同时也方便其他不太熟悉这三个概念的同学。

首先我先上代码,然后解释之。

// 商品类
class ShopProduct {
	public $title;
	public $producerMainName;
	public $producerFirstName;
	public $price;
	
	function __construct($title, $firstName, $mainName, $price) {
		$this->title = $title;
		$this->producerFirstName = $firstName;
		$this->producerMainName = $mainName;
		$this->price = $price;
	}
	
	function getProducer() {
		return "{$this->producerFirstName} {$this->producerMainName}";
	}
	
	function setArray(array $arr) {
		$this->title = $arr[0];
		$this->producerFirstName = $arr[1];
		$this->producerMainName = $arr[2];
		$this->price = $arr[3];
	}
	
	function setTitle($title) {
		$this->title = $title;
	}
}


// 匿名函数的三种定义方法

// 第一种,通过create_function函数
$logging = create_function('$product', 'echo "logging({$product->title})";'); 

// 第二种,这种方法比较明亮直观
$logging = function($product) {
 echo "logging other ({$product->title})";
};

// 第三种,是通过一个函数生成一个匿名函数。其中有用到闭包
// 生成匿名函数、使用闭包
class Func {
	static public function createFunc($num) {
		$count = 0;
		
		return function($product) use ($num, &$count) {
			echo "logging other ({$product->title})<br>\n";
			
			$count += $product->price;
			
			if ($count > $num) {
				echo "销售额超过$num,销售额:$count";
			}
		};
	}
}


调用代码如下,大家可以在本地试一下。

$product = new ShopProduct('test', 'li', 'ying', 5);

$product2 = new ShopProduct('test8', 'li', 'ying', 8);

$process = new Processable();
$process->registerCallBack(Func::createFunc(10));

$process->sale($product);
$process->sale($product2);


结果为:
test: processinglogging other (test)

test8: processinglogging other (test8)

销售额超过13

下边解释一下,或者说总结一下。
1、回调的用途。我们可以注册一些非核心的功能,加入到组件中,相当于对组件进行扩展!
2、匿名函数。主要注意匿名函数的三种生成形式。可以跟回调一起使用。
3、闭包。在上边的那个例子中,返回的匿名函数引用了父作用域的变量,这个被引用的变量称为闭包变量。至于为啥叫闭包。我也不是很清楚。知道原因的同学可以告知一下。谢谢!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: