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)