Home  >  Article  >  Backend Development  >  PHP7之Closure::call javascript closure need for closure google closur

PHP7之Closure::call javascript closure need for closure google closur

WBOY
WBOYOriginal
2016-07-29 08:52:161419browse

Closure class: Anonymous functions (introduced in PHP 5.3) produce objects of this type.
This class can be bound to a class or object, that is, custom methods are dynamically added to the class or object

Methods used before php7

  • Closure::bind: Copy a closure and bind the specified $this object and class scope. This method is the static version of Closure::bindTo()

  • Closure::bindTo: copies the current closure object and binds the specified $this object and class scope. Creates and returns an anonymous function, which has the same function body as the current object and binds the same variables, but can bind different objects or a new class scope.

php7 added

  • Closure::call(): Method was added as a temporary bound object scope to close and easily call its methods. Its performance is much faster than PHP5.6 bindTo.
//bind.php/**
 * Created by PhpStorm.
 * User: bee
 * Date: 2016/4/24
 * Time: 22:35
 */classA {privatestatic$sta = 1;
    private$com = 2;
}
$cl1 = staticfunction() {return A::$sta;
};
$cl2 = function() {return$this->com;
};

$bcl1 = Closure::bind($cl1, null, 'A');
$bcl2 = Closure::bind($cl2, new A(), 'A');
echo$bcl1(), "\n";
echo$bcl2(), "\n";
//bindTo.php/**
 * Created by PhpStorm.
 * User: bee
 * Date: 2016/4/24
 * Time: 22:35
 */classA {function__construct($val) {$this->val = $val;
    }
    functiongetClosure() {//returns closure bound to this object and scopereturnfunction() {return$this->val; };
    }
}

$ob1 = new A(1);
$ob2 = new A(2);

$cl = $ob1->getClosure();
echo$cl(), "\n";

$add = function(){return$this->val+1;
};
$cl = $add->bindTo($ob2);
//与call相比,需要增加()方可被调用echo$cl(), "\n";
//call.php/**
 * Created by PhpStorm.
 * User: bee
 * Date: 2016/4/24
 * Time: 22:35
 */classValue {protected$value;

    publicfunction__construct($value) {$this->value = $value;
    }

    publicfunctiongetValue() {return$this->value;
    }
}

$three = new Value(3);
$four = new Value(4);

$closure = function($delta) {return$this->getValue() + $delta; };
//可直接调用,不用在后面增加()echo$closure->call($three, 3);
echo$closure->call($four, 4);
').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });

The above has introduced Closure::call of PHP7, including closure and php7. I hope it will be helpful to friends who are interested in PHP tutorials.

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