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 STH callback
But we are not sure whether the callback method can be called, so there is a lot of extra work to be done to check whether this callback method can be called.
Is there any better way to tell if the callback method is callable?
We can use callable to force the specified parameter to be a callback type, which guarantees 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 execution, prompt error: Typeerror:argument 1 passed to Dosth () must be callable
The program does not perform to the internal processing of the DOSTH, from the parameter type has already done the inspection processing, plays the protection function.
And if you remove the callable,
<?phpfunction Dosth ($callback) {call_user_func ($callback);} Dosth (' abc ');? >
After execution, prompt warning: warning:call_user_func () expects parameter 1 to be a valid callback, function ' abc ' not found or invalid Functio N Name
The program can perform internal processing to DOSTH, which requires a lot of extra work to check whether the callback method can be called.
Therefore, if the parameter of the method is a callback method, you should add callable to the callback type, which reduces the error of the call and improves the quality of the program.
The above is a small part of the introduction of PHP callable forced to specify the type of callback method, I hope we have some help, if you have any questions please give me a message, small series will promptly reply to you. Thank you very much for your support for topic.alibabacloud.com!