PHPにおける関数の連続呼び出し
ある関数の実行結果を別の関数のパラメータとして渡すことができます。
次の例では、まず数値 2 の2乗を求め、
次にその結果の2乗を求めます:
<?php
function func($num) {
return $num * $num;
}
$res = func(func(2));
echo $res; // 16を出力
?>
もちろん、関数は同じである必要はありません。
たとえば、数値の2乗を返す関数と、数値の3乗を返す関数があるとします:
<?php
function square($num) {
return $num * $num;
}
function cube($num) {
return $num * $num * $num;
}
?>
これらの関数を使って、数値 2 を2乗し、
次にその演算結果を3乗してみましょう:
<?php
$res = cube(square(2));
echo $res;
?>
次に、数値の2乗を返す関数と、2つの数値の合計を求める関数があるとします:
<?php
function square($num) {
return $num * $num;
}
function sum($num1, $num2) {
return $num1 + $num2;
}
?>
これらの関数を使って、数値 2 の2乗と数値 3 の2乗の合計を求めます:
<?php
$res = sum(square(2), square(3));
echo $res;
?>
数値の立方根を返す関数と、小数を小数点以下3桁に丸める関数があるとします:
<?php
function root($num) {
return pow($num, 1/3);
}
function norm($num) {
return round($num, 3);
}
?>
これらの関数を使って、数値 2 の立方根を求め、
それを小数点以下3桁に丸めてください。