PHP Callable forcibly specifies the callback type method, callable callback
If a method needs to accept a callback method as a parameter, we can write
<?phpfunction dosth($callback){call_user_func($callback);}function callback(){echo 'do sth callback';}dosth('callback');?>
Output:
Do something callback
However, we cannot determine whether the callback method can be called. Therefore, we need to do a lot of extra work to check whether the callback method can be called.
Is there any better way to determine whether the callback method can be called?
We can use callable to forcibly specify the parameter as the callback type, which ensures that the callback method must be callable.
For example, the callback method is a non-existent method.
<?phpfunction dosth(callable $callback){call_user_func($callback);}dosth('abc');?>
After the command is executed, the following error occurs: TypeError: Argument 1 passed to dosomething () must be callable.
The program cannot execute the processing in dosomething, and check and process the parameter type to protect it.
If callable is removed
<?phpfunction dosth($callback){call_user_func($callback);}dosth('abc');?>
After the command is executed, a Warning is prompted: Warning: call_user_func () expects parameter 1 to be a valid callback, function 'abc' not found or invalid function name
The program can execute the processing inside dosomething, so it requires a lot of extra work to check whether the callback method can be called.
Therefore, if the method parameter is a callback method, you must add callable to specify the callback type forcibly. This can reduce call errors and improve program quality.
The above is a small compilation of PHP Callable's method to force specify the callback type. I hope it will be helpful to you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!