<p>How are callbacks written in PHP?</p>

[{'answer_id': 48948, 'author': 'Nick Stinemates', 'author_id': 4960, 'author_profile': 'https://Stackoverflow.com/users/4960', 'pm_score': 5, 'selected': False, 'text': '<p>Implementation of a callback is done like so</p>\n\n<pre><code>// This function uses a callback function. \nfunction doIt($callback) \n{ \n    $data = "this is my data";\n    $callback($data); \n} \n\n\n// This is a sample callback function for doIt(). \nfunction myCallback($data) \n{ \n    print \'Data is: \' .  $data .  "\\n"; \n} \n\n\n// Call doIt() and pass our sample callback function\'s name. \ndoIt(\'myCallback\');\n</code></pre>\n\n<p>Displays: Data is: this is my data</p>\n'}, {'answer_id': 49034, 'author': 'yukondude', 'author_id': 726, 'author_profile': 'https://Stackoverflow.com/users/726', 'pm_score': 3, 'selected': False, 'text': '<p>One nifty trick that I\'ve recently found is to use PHP\'s <a href="http://ca.php.net/create_function" rel="noreferrer"><code>create_function()</code></a> to create an anonymous/lambda function for one-shot use. It\'s useful for PHP functions like <code>array_map()</code>, <code>preg_replace_callback()</code>, or <code>usort()</code> that use callbacks for custom processing. It looks pretty much like it does an <code>eval()</code> under the covers, but it\'s still a nice functional-style way to use PHP.</p>\n'}, {'answer_id': 49570, 'author': 'Pat', 'author_id': 238, 'author_profile': 'https://Stackoverflow.com/users/238', 'pm_score': 2, 'selected': False, 'text': '<p>I cringe every time I use <code>create_function()</code> in php. </p>\n\n<p>Parameters are a coma separated string, the whole function body in a string... Argh... I think they could not have made it uglier even if they tried.</p>\n\n<p>Unfortunately, it is the only choice when creating a named function is not worth the trouble.</p>\n'}, {'answer_id': 49581, 'author': 'pilif', 'author_id': 5083, 'author_profile': 'https://Stackoverflow.com/users/5083', 'pm_score': 3, 'selected': False, 'text': '<p>well... with 5.3 on the horizon, all will be better, because with 5.3, we\'ll get closures and with them anonymous functions</p>\n\n<p><a href="http://wiki.php.net/rfc/closures" rel="noreferrer">http://wiki.php.net/rfc/closures</a></p>\n'}, {'answer_id': 50515, 'author': 'SeanDowney', 'author_id': 5261, 'author_profile': 'https://Stackoverflow.com/users/5261', 'pm_score': 3, 'selected': False, 'text': '<p>You will want to verify whatever your calling is valid. For example, in the case of a specific function, you will want to check and see if the function exists:</p>\n\n<pre><code>function doIt($callback) {\n    if(function_exists($callback)) {\n        $callback();\n    } else {\n        // some error handling\n    }\n}\n</code></pre>\n'}, {'answer_id': 50596, 'author': 'Steve Clay', 'author_id': 3779, 'author_profile': 'https://Stackoverflow.com/users/3779', 'pm_score': 8, 'selected': True, 'text': '<p>The manual uses the terms "callback" and "callable" interchangeably, however, "callback" traditionally refers to a string or array value that acts like a <a href="http://en.wikipedia.org/wiki/Function_pointer" rel="noreferrer">function pointer</a>, referencing a function or class method for future invocation. This has allowed some elements of functional programming since PHP 4. The flavors are:</p>\n\n<pre><code>$cb1 = \'someGlobalFunction\';\n$cb2 = [\'ClassName\', \'someStaticMethod\'];\n$cb3 = [$object, \'somePublicMethod\'];\n\n// this syntax is callable since PHP 5.2.3 but a string containing it\n// cannot be called directly\n$cb2 = \'ClassName::someStaticMethod\';\n$cb2(); // fatal error\n\n// legacy syntax for PHP 4\n$cb3 = array(&amp;$object, \'somePublicMethod\');\n</code></pre>\n\n<p>This is a safe way to use callable values in general:</p>\n\n<pre><code>if (is_callable($cb2)) {\n    // Autoloading will be invoked to load the class "ClassName" if it\'s not\n    // yet defined, and PHP will check that the class has a method\n    // "someStaticMethod". Note that is_callable() will NOT verify that the\n    // method can safely be executed in static context.\n\n    $returnValue = call_user_func($cb2, $arg1, $arg2);\n}\n</code></pre>\n\n<p>Modern PHP versions allow the first three formats above to be invoked directly as <code>$cb()</code>. <code>call_user_func</code> and <code>call_user_func_array</code> support all the above.</p>\n\n<p>See: <a href="http://php.net/manual/en/language.types.callable.php" rel="noreferrer">http://php.net/manual/en/language.types.callable.php</a></p>\n\n<p>Notes/Caveats: </p>\n\n<ol>\n<li>If the function/class is namespaced, the string must contain the fully-qualified name. E.g. <code>[\'Vendor\\Package\\Foo\', \'method\']</code></li>\n<li><code>call_user_func</code> does not support passing non-objects by reference, so you can either use <code>call_user_func_array</code> or, in later PHP versions, save the callback to a var and use the direct syntax: <code>$cb()</code>;</li>\n<li>Objects with an <a href="http://us2.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.invoke" rel="noreferrer"><code>__invoke()</code></a> 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.</li>\n<li>The legacy <code>create_function()</code> creates a global function and returns its name. It\'s a wrapper for <code>eval()</code> and anonymous functions should be used instead.</li>\n</ol>\n'}, {'answer_id': 1272403, 'author': 'goliatone', 'author_id': 125083, 'author_profile': 'https://Stackoverflow.com/users/125083', 'pm_score': 3, 'selected': False, 'text': '<p><code>create_function</code> did not work for me inside a class. I had to use <code>call_user_func</code>.</p>\n\n<pre><code>&lt;?php\n\nclass Dispatcher {\n    //Added explicit callback declaration.\n    var $callback;\n\n    public function Dispatcher( $callback ){\n         $this-&gt;callback = $callback;\n    }\n\n    public function asynchronous_method(){\n       //do asynch stuff, like fwrite...then, fire callback.\n       if ( isset( $this-&gt;callback ) ) {\n            if (function_exists( $this-&gt;callback )) call_user_func( $this-&gt;callback, "File done!" );\n        }\n    }\n\n}\n</code></pre>\n\n<p>Then, to use:</p>\n\n<pre><code>&lt;?php \ninclude_once(\'Dispatcher.php\');\n$d = new Dispatcher( \'do_callback\' );\n$d-&gt;asynchronous_method();\n\nfunction do_callback( $data ){\n   print \'Data is: \' .  $data .  "\\n";\n}\n?&gt;\n</code></pre>\n\n<p>[Edit]\nAdded a missing parenthesis. \nAlso, added the callback declaration, I prefer it that way.</p>\n'}, {'answer_id': 2523807, 'author': 'Bart van Heukelom', 'author_id': 85821, 'author_profile': 'https://Stackoverflow.com/users/85821', 'pm_score': 6, 'selected': False, 'text': '<p>With PHP 5.3, you can now do this:</p>\n\n<pre><code>function doIt($callback) { $callback(); }\n\ndoIt(function() {\n    // this will be done\n});\n</code></pre>\n\n<p>Finally a nice way to do it. A great addition to PHP, because callbacks are awesome.</p>\n'}, {'answer_id': 11657728, 'author': 'Kendall Hopkins', 'author_id': 188044, 'author_profile': 'https://Stackoverflow.com/users/188044', 'pm_score': 2, 'selected': False, 'text': '<p>For those who don\'t care about breaking compatibility with PHP <code>&lt; 5.4</code>, I\'d suggest using type hinting to make a cleaner implementation.</p>\n\n<pre><code>function call_with_hello_and_append_world( callable $callback )\n{\n     // No need to check $closure because of the type hint\n     return $callback( "hello" )."world";\n}\n\nfunction append_space( $string )\n{\n     return $string." ";\n}\n\n$output1 = call_with_hello_and_append_world( function( $string ) { return $string." "; } );\nvar_dump( $output1 ); // string(11) "hello world"\n\n$output2 = call_with_hello_and_append_world( "append_space" );\nvar_dump( $output2 ); // string(11) "hello world"\n\n$old_lambda = create_function( \'$string\', \'return $string." ";\' );\n$output3 = call_with_hello_and_append_world( $old_lambda );\nvar_dump( $output3 ); // string(11) "hello world"\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/48947', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4960/']