Implement PHP events based on C # event ideas
Event definition
When we use the delegate scenario, we would like to have such two roles appearing: broadcasters and Subscribers. We need these two roles to implement a very common scenario of subscribing and broadcasting.
The broadcaster's role should have the ability to include a delegate field to emit a broadcast by invoking a delegate. Subscribers should have the ability to decide when to start or stop a subscription by calling + = and-=.
An event is a word that describes the pattern of the scene. Events are a subset of delegates that are born to meet the needs of the broadcast/subscription mode.
Simple implementation of events in C #
usingSystem;namespaceconsoleapplication2{classProgram {Static voidMain (string[] args) {ObServer ob=NewObServer (); Ob. Changed+=Change ; Ob. Trigger ("Hello Kitty"); Console.ReadLine (); } Static voidChange (stringoutput) {Console.WriteLine (output); } } classObServer {/// /// events // Public Eventaction<string>Changed; /// /// trigger event /// /// Public voidTrigger (stringinit) {Changed (init); } }}
The same idea, my understanding of the event is actually a function of the execution of the B-function, the above-mentioned in the case of only when the INIT is executed automatically trigger the delegate's changing to bind the execution of print, the focus is on
Observer itself does not realize changing want to just business to leave the business outside to deal with this in dealing with the coupling of complex systems to facilitate.
In combination with this idea, PHP implements similar events
Phpclassobservice{ Public $even=NULL; Public functionTrigger$init){ Call_user_func($this->even,$init); }}$ob=NewObservice ();$ob->even = "Chanage";$ob->trigger ("Hello kitty!");functionChanage ($str){ Echo($str);}?>
Summary: I did not check the code of the actual implementation of PHP, but based on personal understanding, combined with C # code to implement the event.