How are callbacks written in PHP?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The manual uses the terms "callback" and "callable" interchangeably, however, "callback" traditionally refers to a string or array value that acts like a function pointer, referencing a function or class method for future invocation. This has allowed some elements of functional programming since PHP 4. The flavors are:
This is a safe way to use callable values in general:
Modern PHP versions allow the first three formats above to be invoked directly as
$cb().call_user_funcandcall_user_func_arraysupport all the above.See: http://php.net/manual/en/language.types.callable.php
Notes/Caveats:
['Vendor\Package\Foo', 'method']call_user_funcdoes not support passing non-objects by reference, so you can either usecall_user_func_arrayor, in later PHP versions, save the callback to a var and use the direct syntax:$cb();__invoke()method (including anonymous functions) fall under the category "callable" and can be used the same way, but I personally don’t associate these with the legacy "callback" term.create_function()creates a global function and returns its name. It’s a wrapper foreval()and anonymous functions should be used instead.