: This article mainly introduces the use of closures in PHP. For more information about PHP tutorials, see. Use of closures in PHP
Example 1
ObjectInstance, then register the service using the set () method, and get the service using the get () method. * We can see that $ di-> set () uses anonymous functions. We have registered both zhangsan and lisi services in advance, both of which are User-class instances, * $ di-> set is not actually instantiated. Instead, the anonymous function is executed at $ di-> get () andObjectReturn, * this achieves ** on-demand instantiation, without instantiating, improving efficiency **. */ClassDi {private $ _ factory; publicfunctionset ($ id, $ value) {$ this-> _ factory [$ id] = $ value;} publicfunctionget ($ id) {$ value = $ this-> _ factory [$ id]; return $ value () ;}} classUser {private $ _ username; function _ construct ($ username = "") {$ this-> _ username = $ username;} functiongetUserName () {return $ this-> _ username ;}} // starting from here, we can see $ di = new Di (); $ di-> set ("zhangsan", function () {returnnew User ('zhangsan ');}); $ di-> set ("lisi", function () {returnnew User ("") ;}); echo $ di-> get ("zhangsan ") -> getUserName (); echo $ di-> get ("lisi")-> getUserName ();
Example 2
/*** A basic shopping cart, including some added items and the quantity of each item. * One method is used to calculate the total price of all items in the shopping cart. This method uses closure as the callback function. */ClassCart {const PRICE_BUTTER = 1.00; const PRICE_MILK = 3.04; const PRICE_EGGS = 6.95; protected $ products = array (); publicfunctionadd ($ product, $ quantity) {$ this-> products [$ product] = $ quantity;} publicfunctiongetQuantity ($ product) {returnisset ($ this-> products [$ product])? $ This-> products [$ product]: FALSE;} publicfunctiongetTotal ($ tax) {$ total = 0.00; $ callback = function ($ quantity, $ product) use ($ tax, & $ total) {$ pricePerItem = constant (_ CLASS __. ": PRICE _". strtoupper ($ product); $ total + = ($ pricePerItem * $ quantity) * ($ tax + 1.0) ;}; array_walk ($ this-> products, $ callback ); return round ($ total, 2) ;}$ my_cart = new Cart; // add an entry to the Cart $ my_cart-> add ('butter ', 1 ); $ my_cart-> add ('milk', 3); $ my_cart-> add ('eggs', 6); // you can obtain the total price, with a sales tax of 5%. print $ my_cart-> getTotal (0.05 ). "\ n"; // The result is 54.29
The above introduces the use of closures in PHP, including some content, and hope to be helpful to friends who are interested in PHP tutorials.