这是我目前的代码结构:
$i = 5; // the number of attempt which my app does to achieve success
for ( $i; $i > 0; $i-- ) {
try {
$bool = crawl_links();
if ( $bool ) {
// function above is done successfully
$i = 0;
} else {
// function above needs to try again
throw new Exception('Fetch links is failed');
}
} catch ( Exception $e ) {
// insert $e into Log.php file
}
}
我还有其他五个函数(类似于crawl_links()
),我想在同一个结构中调用它们。好吧,我通过多次复制并粘贴代码并用crawl_links()
替换其他函数来做到这一点。但它看起来很难看。
有没有更好的方法来处理它?</ p>
答案 0 :(得分:1)
创建一个函数:
function call_with_attempts(callable $function, $attempts = 5) {
while ($attempts-- > 0) {
try {
if ($function()) {
return;
}
throw new Exception("$function failed");
} catch (Exception $e) {
trigger_error($e->getMessage());
}
}
}
call_with_attempts(function () {
// Custom function
return true;
});
call_with_attempts('crawl_links', 3);
将参数传递给函数
如果要将参数传递给函数,请使用call_user_func_array
:
function call_with_attempts(callable $function, array $params = [], $attempts = 5) {
// ...
if (call_user_func_array($function, $params)) {
return;
}
// ...
}
样本用法:
call_with_attempts(function () {
echo var_export(func_get_args(), true), PHP_EOL;
return true;
}, ['a', 'b']);
示例输出:
array (
0 => 'a',
1 => 'b',
)