If a method needs to accept a callback method as an argument, we can write
<?php
function Dosth ($callback) {
call_user_func ($callback);
}
function callback () {
echo ' do sth callback ';
}
Dosth (' callback ');
? >
Output:
Do STH callback
But we are not sure if the callback method can be invoked, so a lot of extra work needs to be done to check whether this callback method can be invoked.
What better way to tell if a 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 method that does not exist
<?php
function Dosth (callable $callback) {
call_user_func ($callback);
}
Dosth (' abc ');
? >
Prompt error after execution: typeerror:argument 1 passed to Dosth () must is callable
The program does not perform the processing within the DOSTH, which has been checked and processed from the parameter type, and has a protective effect.
And if you remove the callable
<?php
function Dosth ($callback) {
call_user_func ($callback);
}
Dosth (' abc ');
? >
After execution, prompt warning: warning:call_user_func () expects parameter 1 to is a valid callback, function ' abc ' not found or invalid Functio N Name
The program can perform the processing within the DOSTH, which requires a lot of extra work to check whether the callback method can be invoked.
Therefore, if the method's argument is a callback method, it should be added with the callable force specified as the callback type, which can reduce the error of the call and improve the quality of the program.
The above is a small set to introduce the PHP callable forced to specify the type of callback method, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!