Передать функцию анонимного обратного вызова в качестве аргумента в функцию?

Я хочу отправить функцию в другую функцию, которая будет выполняться позже внутри этой функции. Идея похожа на функцию успеха обратного вызова в jQuery.

Идея заключается в следующем:

function my_function($args)
{
// ...

// Code that creates the $result variable

// ..

// Execute the calback function, how??:
$args['callback_function']; // Handle the $result
}

$args = array(
'callback_function' => function($result)
{
// $result created in my_function()
}
);
my_function($args);

0

Решение

Используя свой собственный пример, вы можете сделать это следующим образом …

function my_function($args)
{
$res= "your value here";

$args['callback_function']($res); // Handle the $result
}

$args = array(
'callback_function' => function($result)
{
var_dump($result);
}
);
my_function($args);
1

Другие решения

Вы можете сделать это так:

$args['callback_function']($result);

Или вот так:

call_user_func($args['callback_function'], $result);

Для дополнительной информации: http://php.net/manual/en/function.call-user-func.php

пример

function my_function($args)
{
// ...
// Code that creates the $result variable
$result = 1;
// ...

call_user_func($args['callback_function'], $result);
}

$args = array(
'callback_function' => function($result) {
echo ++$result;
}
);

my_function($args);

Выход

2
1

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector