Created
June 26, 2015 08:54
-
-
Save lbp0200/a88b6ece1722b4ed03d8 to your computer and use it in GitHub Desktop.
callback demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| class person { | |
| public $name; | |
| public $price; | |
| function __construct($name, $price) { | |
| $this->name = $name; | |
| $this->price = $price; | |
| } | |
| } | |
| /** | |
| * | |
| */ | |
| class ProcessSale { | |
| private $callbacks = array(); | |
| function __construct() { | |
| # code... | |
| } | |
| function registerCallback($callBack) { | |
| if (!is_callable($callBack)) { | |
| throw new Exception('can not call it'); | |
| } | |
| $this->callbacks[] = $callBack; | |
| } | |
| function sale($product) { | |
| print "{$product->name}:progressing \n"; | |
| foreach ($this->callbacks as $callback) { | |
| call_user_func($callback, $product); | |
| // $callback($product); | |
| } | |
| } | |
| } | |
| $loger = create_function('$product', 'print $product->name."\n";'); | |
| $processor = new ProcessSale(); | |
| $processor->registerCallback($loger); | |
| $processor->sale(new person('shoes', 6)); | |
| print "\n"; | |
| $processor->sale(new person('djfiid', 9)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment