PHP Callable forces the method to specify the callback type

高洛峰
Release: 2023-03-04 14:30:01
Original
1102 people have browsed it

If a method needs to accept a callback method as a parameter, we can write like this

Copy after login

Output:

do sth callback

But we It cannot be determined whether the callback method can be called, so a lot of extra work needs to be done to check whether the callback method can be called.

Is there any better way to determine whether the callback method is callable?
We can use callable to force the specified parameter to be a callback type, which ensures that the callback method must be callable.

For example, the callback method is a non-existent method

Copy after login

After execution, an error message is displayed: TypeError: Argument 1 passed to dosth() must be callable
The program cannot execute the internal processing of dosth. The parameter type has been checked and processed for protection.

And if the callable is removed

Copy after login

After execution, a warning is displayed: 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 internal processing of dosth, so a lot of extra work needs to be done to check whether this callback method can be called.

Therefore, if the parameter of the method is a callback method, callable should be added to force it to be specified as the callback type. This can reduce calling errors and improve the quality of the program.

The above is the method that the editor introduces to you for PHP Callable to forcefully specify the callback type. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. I would also like to thank you all for your support of the PHP Chinese website!

For more articles on how PHP Callable forces the callback type to be specified, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!