Callback. let's take a look at how PHP implements callback 1. first, create an object classProduct {public $ name; // to facilitate the test function _ construct ($ name) {$ this-& gt; name $ name ;}} 2. use callback classProcessSale {pr...
Callback. let's take a look at how PHP implements callback.
1. first create an object
Class Product {
Public $ name; // to facilitate testing
Function _ construct ($ name ){
$ This-> name = $ name;
}
}
2. use callback
Class ProcessSale {
Private $ callbacks;
// Set the 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 "));
By sunwei-07