PHP Callable forcibly specifies the callback type method, callable callback

Source: Internet
Author: User

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!

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.