PHP callable methods for forcing a callback type to be specified

Source: Internet
Author: User
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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.