Closure class in PHP

Source: Internet
Author: User
Tags php template
This article is mainly to share with you the Closure class in PHP, PHP Closure class is used to represent anonymous functions of the class, anonymous functions (introduced in PHP 5.3) will produce this type of object, the Closure class summary is as follows:

Closure {    __construct (void) public    static Closure bind (Closure $closure, Object $newthis [, Mixed $newscope = ' Static ']) public    Closure BindTo (Object $newthis [, Mixed $newscope = ' static ']}

Method Description:

closure::__construct-Constructors for prohibiting instantiation
closure::bind-copy a closure that binds the specified $this object and class scope.
closure::bindto-Copy the current closure object, binding the specified $this object and the class scope.

In addition to the methods listed here, there is a __invoke method. This is to maintain consistency with other objects that implement the __invoke () Magic method, but the process of calling a closure object is not related to it.

The closure::bind and closure::bindtoare described below.

Closure::bind is a static version of Closure::bindto, which is described below:

public static Closure bind (Closure $closure, Object $newthis [, Mixed $newscope = ' static '])

Closure represents a closure object that needs to be bound.
Newthis represents an object that needs to be bound to a closure object, or null to create an unbound closure.
Newscope represents a class scope that you want to bind to a closure, you can pass in an example of a class name or class, and the default value is ' static ', which means no change.

When the method succeeds, it returns a new Closure object that returns false on failure.

Example Description:

<?php/**  * Copies a closure that binds the specified $this object and class scope.  *  * @author crazy old driver  */class Animal {    private static $cat = "Cat";    Private $dog = "dog";    Public $pig = "Pig";}  /* Get Animal class static Private member Property */$cat = static function () {    return Animal:: $cat;};/ *  * Get animal Instance Private member properties */$dog = function () {    return $this->dog;};/ *  * Get animal Instance public member Properties */$pig = function () {    return $this->pig;}; $bindCat = Closure::bind ($cat, NULL, New Animal ());//The scope of the Animal instance is bound to the closure, but no $this object is bound to the closure $binddog = Closure::bind ($dog, New Animal (), ' Animal ');//Bind the scope of the Animal class to the closure, and bind the Animal instance object as a $this object to the closure $bindpig = Closure::bind ($pig, New Animal ()) ;//Bind the animal instance object as a $this object to the closure, preserving the original scope of the closure echo $bindCat (), ' <br> ';//based on binding rules, allow closures to get animal class static private member properties by scope-scoped operator Echo $bindDog (), ' <br> ';//based on binding rules, allow closures to get animal instance private member properties through the bound $this object (animal instance object) echo $bindPig (), ' <br> ';/ According to binding rules, allow closures to get animal instance public member properties through the bound $this object?>

Output:

Cat
Dog
Pig

closure::bindto -Copy the current closure object, binding the specified $this object and class scope, as described below:

Public Closure Closure::bindto (Object $newthis [, Mixed $newscope = ' static '])

Newthis represents an object that is bound to a closure object, or null to unbind.
Newscope represents a class scope that is associated to a closure object, can pass in an example of a class name or class, and the default value is ' static ', which means no change.

The method creates and returns a closure object that binds the same variable as the current object, but can bind different objects or bind a new class scope. The bound object determines the value of the $this in the returned closure object, and the class scope determines which methods the returned closure object can invoke, that is, the method that $this can call at this time, the same scope as the Newscope class.

Example 1:

<?phpfunction __autoload ($class) {    require_once "$class. php";} $template = new template; $template->render (new article, ' tpl.php ');? >

template.php template class

<?php/**  * Template class for rendering output  *  * @author crazy old driver  */class template{    /**     * Rendering Method     *     * @access Public      * @param obj information class     * @param string template file name *    /Public Function render ($context, $TPL) {        $ Closure = function ($TPL) {            ob_start ();            Include $tpl;            return Ob_end_flush ();        };        $closure = $closure->bindto ($context, $context);        $closure ($TPL);}    }

Article.php Information class

<?php/**  * Article Information class  *  * @author crazy old driver  */class article{    Private $title = "This is the title of the article";    Private $content = "This is the content of the article";}

tpl.php template file

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

The runtime ensures that the above files are in the sibling directory.

Output:

This is the article title

This is the content of the article

Example 2:

<?php/**  * Adding new methods to classes dynamically *  * @author crazy old driver */trait dynamictrait {    /**     * method exists in the auto-call     class    */Public function __call ($name, $args) {        if (is_callable ($this-, $name)) {            return Call_user_func ($this-, $name, $ args);        } else{            throw new \runtimeexception ("Method {$name} does not exist");        }    }    /**     * Add Method     *    /Public Function __set ($name, $value) {        $this-$name = is_callable ($value)?             $value->bindto ($this, $this):             $value;    }} /**  * Only with attributes without method animal class *  * @author crazy old driver */class Animal {use    dynamictrait;    Private $dog = ' dog ';} $animal = new animal;//Adds a method to the animal instance to get the private property of the instance $dog$animal->getdog = function () {    return $this->dog;}; echo $animal->getdog ();? >

Output:

Dog

Example 3:

<?php/** * A basic shopping cart, including some already added items and the quantity of each item * * @author crazy old driver */class Cart {//define commodity price Const PRICE_BUTTER = 1.00;    Const PRICE_MILK = 3.33;     Const PRICE_EGGS = 8.88;    Protected $products = Array (); /** * Add goods and quantities * * @access public * @param string commodity name * @param string number of goods */Public function    Add ($item, $quantity) {$this->products[$item] = $quantity; }/** * Get a single item quantity * * @access public * @param string commodity name */Public Function getquantity ($item)    {return isset ($this->products[$item])? $this->products[$item]: FALSE; }/** * Get Total Price * * @access public * @param string tax rate */Public Function gettotal ($tax) {$        Total = 0.00; $callback = function ($quantity, $item) use ($tax, & $total) {$pricePerItem = constant (__class__). "::P rice_".            Strtoupper ($item));        $total + = ($pricePerItem * $quantity) * ($tax + 1.0);      };           Array_walk ($this->products, $callback);    Return round ($total, 2);; }} $my _cart = new cart;//Add the goods and corresponding quantities $my_cart->add (' butter ', ten) to the shopping cart, $my _cart->add (' Milk ', 3); $my _cart->add (' Eggs ', 12);//Hit out the total price, which has 5% sales tax. Echo $my _cart->gettotal (0.05); >

Output:

132.88

Additional note: Closures can be used to connect external variables using the key.

Summary: The rational use of closures can make the code more concise and refined.
Related recommendations:

Introducing closure usage examples in PHP

Examples of closure usages in PHP

Introduction to Closure in PHP

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.