Home > Article > Backend Development > PHP Callable forces the method to specify the callback type
If a method needs to accept a callback method as a parameter, we can write like this
<?php function dosth($callback){ call_user_func($callback); } function callback(){ echo 'do sth callback'; } dosth('callback'); ?>
Output:
do sth callback
But we can’t be sure whether the callback method can be called, so a lot of extra work needs to be done. Check whether this callback method can be called.
Is there any better way to determine whether the callback method is callable?
We can use callable to force the specified parameter to be a callback type, which ensures that the callback method must be callable.
For example, the callback method is a non-existent method
<?php function dosth(callable $callback){ call_user_func($callback); } dosth('abc'); ?>
After execution, an error message is displayed: TypeError: Argument 1 passed to dosth() must be callable
The program cannot execute the internal processing of dosth, from the parameters The type has been checked and processed for protection.
And if the callable is removed
<?php function dosth($callback){ call_user_func($callback); } dosth('abc'); ?>
After execution, a warning is displayed: Warning: call_user_func() expects parameter 1 to be a valid callback, function 'abc' not found or invalid function name
The program can be executed to dosth Internal processing, so a lot of extra work needs to be done to check whether this callback method can be called.
Therefore, if the parameter of the method is a callback method, callable should be added to force it to be specified as the callback type. This can reduce calling errors and improve the quality of the program.
The above is the method that the editor introduces to you to force the callback type to be specified in PHP Callable. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. I would also like to thank you all for your support of the PHP Chinese website!
For more articles related to PHP Callable’s method of forcing the callback type to be specified, please pay attention to the PHP Chinese website!