このPHPコードスニペットを参照してください。
try {
/* do something */
} catch (Exception $e) {
echo $e->getMessage();
}
try {
/* do something else */
} catch (Exception $e) {
echo $e->getMessage();
}
try {
/* do something other */
} catch (Exception $e) {
echo $e->getMessage();
}
望ましいシナリオ:
function run($code) {
try {
<< execute $code >>;
} catch (Exception $e) {
echo $e->getMessage();
}
}
run({ /* do something */ });
run({ /* do something else */ });
run({ /* do something other */ });
PHPでより多くの名前付き関数を作成せずに、このようなものを体系化することは可能ですか?
匿名関数を使用できます:
<?php
function run($code) {
try {
$code();
} catch (Exception $e) {
echo $e->getMessage() . PHP_EOL;
}
}
// Simple anonymous function
run(function ()
{
echo "Hello" . PHP_EOL;
throw new Exception("1 throws");
});
// Anonymous function stored in a variable
$somePieceOfCode = function ()
{
echo "Hello 2" . PHP_EOL;
throw new Exception("2 throws");
};
run($somePieceOfCode);
// Use external variables in the anonymous function
$message = "Hello";
$number = 3;
run(function () use ($message, $number)
{
echo "$message $number" . PHP_EOL;
throw new Exception("3 throws");
});
// Store and execute your anonymous functions in an array
$functionArray = [
function ()
{
echo "Array 1" . PHP_EOL;
throw new Exception("Array 1 throws");
},
function ()
{
echo "Array 2" . PHP_EOL;
throw new Exception("Array 2 throws");
},
function ()
{
echo "Array 3" . PHP_EOL;
throw new Exception("Array 3 throws");
}
];
foreach ($functionArray as $func)
{
run($func);
}
この出力:
Hello
1 throws
Hello 2
2 throws
Hello 3
3 throws
Array 1
Array 1 throws
Array 2
Array 2 throws
Array 3
Array 3 throws
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加