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

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

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

// 商品类
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、闭包。在上边的那个例子中,返回的匿名函数引用了父作用域的变量,这个被引用的变量称为闭包变量。至于为啥叫闭包。我也不是很清楚。知道原因的同学可以告知一下。谢谢!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值