php uses Callable Closure to force callback types

  • 2021-08-12 02:14:40
  • OfStack

php uses Callable Closure to force callback types

If a method needs to accept a callback method as an argument, we can write


<?php 
function testCallBack($callback){ 
  call_user_func($callback); 
} 
 
function callback(){ 
  echo 'do sth callback'; 
} 
 
testCallBack('callback'); 
?> 

But we can't be sure if the callback method can be called, so we need to do a lot of extra work to check whether the callback method can be called.

Is there a better way to judge whether the callback method can be called?

We can use callable to force the parameter to be of callback type, which ensures that the callback method must be callable.


<?php 
function testCallBack($callback){ 
  call_user_func($callback); 
} 
 
function callback(){ 
  echo 'do sth callback'; 
} 
 
testCallBack('abc'); 
?> 

After execution, a warning is prompted: Warning: call_user_func () expects parameter 1 to be a valid callback, function 'abc' not found or invalid function name programs can perform processing inside dosth, which requires a lot of extra work to check whether this callback method can be called.


<?php 
function testCallBack(callable $callback){ 
  call_user_func($callback); 
} 
 
function callback(){ 
  echo 'do sth callback'; 
} 
 
testCallBack('abc'); 
?> 

After execution, it prompts an error: TypeError: Argument 1 passed to testCallBack () must be callable program can't execute the internal processing of dosth, and it has been checked from the parameter type to play a protective role.


<?php 
$f = function () { 
  return 100; 
}; 
 
function testClosure(Closure $callback) { 
  return $callback(); 
} 
 
$a = testClosure($f); 
print_r($a); //100 
exit; 

Therefore, if the parameter of the method is a callback method, you should add callable to force it to be a callback type, which can reduce calling errors and improve the quality of the program.

If you have any questions, please leave a message or go to this site community to exchange and discuss, thank you for reading, hope to help everyone, thank you for your support to this site!


Related articles: