Developer

【PHP基礎】ユーザー定義関数
2021.02.05
Lv1

【PHP基礎】ユーザー定義関数

ユーザー定義関数

用意されている関数とは別に、ユーザーが独自に関数を作成することもできます。

▼構文(引数なしの場合)

1
2
3
4
function() {
    処理
    return 戻り値;
}

▼構文(引数ありの場合)

1
2
3
4
function(引数) {
    処理
    return 戻り値;
}

※戻り値がない場合は、returnを省略するか戻り値のみを省略します。

■身長と体重を入力するとBMI指数を返す関数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<?php
    // 身長と体重を渡すとBMI指数を返す関数
    function calc_bmi($height_cm, $weight) {
        $height_m = $height_cm / 100;
        $bmi = $weight / ($height_m * $height_m);
        return $bmi;
    }
?>
<?php
    $title = 'ユーザー定義関数サンプル1';
    $bmi;
 
    if(isset($_GET['height_cm']) && isset($_GET['weight'])) {
        $bmi = calc_bmi($_GET['height_cm'], $_GET['weight']);
    }
 
?>
 
<!DOCTYPE html>
<html>
<head>
    <title><?php print($title); ?></title>
</head>
<body>
    <h1><?php print($title); ?></h1>
    <h2>BMI指数を表示します</h2>
 
    <form action="bmi.php" method="get">
        <label>身長(cm):</label><input type="text" name="height_cm">
        <br>
        <label>体重(kg):</label><input type="text" name="weight">
        <br>
        <button>計算</button>
    </form>
 
    <?php
        if(isset($bmi)) {
            echo "<div>BMI指数は{$bmi}です。<div>";
        }
    ?>
</body>
</html>

▼表示結果

PHP基礎 連載目次リンク

PHP基礎 連載目次