回调函数

  回调函数的应用场景无须多述,在C/C++中充斥着无数的回调函数典型用例。 这里只是简单给出PHP中回调函数的使用规则。见如下示例代码和关键性注释: 

<?php
class Product {
    public $name;
    public $price;
    public function __construct($name, $price) {
        $this->name = $name;
        $this->price = $price;
    }
}

class ProcessSale {
    private $callbacks;
    function registerCallback($cb) {
        if (!is_callable($cb)) {
            throw new Exception("callback not callable.");
        }
        $this->callbacks[] = $cb;
    }
    function sale($product) {
        print "{$product->name}: processing \n";
        foreach ($this->callbacks as $cb) {
            //以下两种调用方式均可。
            call_user_func($cb, $product);
            $cb($product);
        }
    }
}

$logger = function($product) {
    print "    logging ({$product->name})\n";
};

$processor = new ProcessSale();
$processor->registerCallback($logger);
$processor->sale(new Product("shoes",6));
print "\n";
$processor->sale(new Product("coffee",6));

 

posted @ 2022-05-23 22:28  今天又双叒叕在敲代码  阅读(18)  评论(0编辑  收藏  举报