Home >Backend Development >PHP Tutorial >PHP callback method_PHP tutorial

PHP callback method_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:46:241337browse

Callback, no need to explain, let’s take a look at how to implement callback in PHP

1. First create an object
class Product{
public $name; //For convenience of testing

function __construct($name){
$this->name=$name;
}
}

2. Use callbacks
class ProcessSale{
private $callbacks;

//Set callback method
function registerCallBack($callback){
If(!is_callable($callback)){
         throw new Exception("xxxxxx");
}

$this->callbacks[]=$callback;
}

function sale($product){
Print "{$product->name}:processing n";

foreach($this->callbacks as $callback){
​​ call_user_func($callback,$product);
}
}
}

3. Test
$logger = function($product){
print "logging ({$product->name})";
}

$processor = new ProcessSale();
$processor->registerCallBack($logger);

$processor->sale(new Product("Test"));

Author: sunwei-07

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/478584.htmlTechArticleCallback, no need to explain, let’s take a look at how to implement callback in PHP 1. First create an object class Product{ public $name; //For the convenience of testing function __construct($name){ $this-name...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn