Closure::bind Usage in PHP (manual recording)

Source: Internet
Author: User

Manual closure::bind- Copy a closure that binds the specified $this object and class scope.

Specific parameters can be seen in the manual, here to record the practical use of this method.

1<?PHP2 3 Trait metatrait4 {5     Private $methods= [];6 7      Public functionAddmethod ($methodName,$methodCallable)8     {9         if(!is_callable($methodCallable))Ten             Throw NewInvalidArgumentException (' Second param must be callable '); One  A         //changing the scope to Get_called_class object -         $this->methods[$methodName] = Closure::bind ($methodCallable,$this,Get_called_class ()); -  the     } -  -      Public function__call ($methodName,Array $args) -     { +         if(isset($this->methods[$methodName])){ -             return Call_user_func_array($this->methods[$methodName],$args); +         } A  at         Throw NewRuntimeException (' There is-no method with the given name-to-call '); -  -     } -  - } -  in classHackthursday - { to      Usemetatrait; +  -     Private $dayOfWeek= ' Thursday '; the } *  $ Panax Notoginseng $test=NewHackthursday (); - $test->addmethod (' When ',function(){ the     return $this-DayOfWeek; + }); A  the Echo $test->when ();//Thursday

In fact, this method is a static version of Closure::bindto () that was previously said, and the problem with PHP when using reflection, as well as a solution to this article to see a deeper understanding.

Closure::bind Usage in PHP (manual recording)

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.