Reputation: 13931
I found code similar to this:
function function_1($callback)
{
// not related code removed
$callback($p);
}
How to call this function? What shall I put in $callback
parameter?
Lets say, I want to use function called function_2($p)
.
Upvotes: 3
Views: 125
Reputation: 21003
in older php versions, you would call it with
function_1("function_2");
but in php 5.3, you could do
$function_2 = function($p) {
};
function_1($function_2);
For further reference, read Anonymous functions, Callbacks and call_user_func in the PHP manual.
Upvotes: 0
Reputation:
Here's the full explanation you want, straight from the php docs: Callbacks.
If you're on php 5.3+, you can pass a lambda (aka anonymous function):
<?php function_1(function ($p) { ... });
If you need support for previous versions of php, you need to define a regular function or instance method. Since the code you've shown is using $callback()
instead of call_user_func($callback)
, you shouldn't need this.
<?php
// without a class
function function_2 ($p) { ... }
function_1('function_2');
// with a class
class A {
public function function_2 ($p) { ... }
public function doIt () {
function_1(array($this, 'function_2'));
}
}
Upvotes: 4
Reputation: 7918
Run it:
function function_2()
{
echo 'done';
}
function function_1($callback)
{
// not related code removed
call_user_func($callback);
}
function_1("function_2");
Upvotes: 1
Reputation: 1222
function test($param)
{
}
function function_1($callback)
{
// not related code removed
$callback($p);
}
function_1("test")
Upvotes: 0