PHP Callable method to force the specified callback type _php instance

Source: Internet
Author: User

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!

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.