Pages

Subscribe:

Labels

2011-11-23

PHPの基礎~関数(ユーザ定義関数)その3

前回前々回と関数についてまとめました。
今回は関数についての最後です。

引数のデフォルトに関してまとめます。
引数は関数を使うために引き渡す値です。
毎回変化する可能性があるので変数を設定していましたが、
そこに決まった数字を入れておくこともできます。
それが引数のデフォルトです。

例えばお給料の計算をする関数を作りたいというとき、
計算に時給が使われる場合など決まった数字になることが多いと思います。
そのようなときに数値をあらかじめ設定しておき、
最初からその値が引数として渡ってきているようにすることができます。

前回作った「plusTwoNumbers」の関数に当てはめてみると
以下のようになります。
<?php
function plusTwoNumbers($one,$two=10){
    $ans = $one + $two;
    return $ans;
}

$a = 5;
$b = 8;
$c = 3;
$d = 7;

$ans1 = plusTwoNumbers($a);
$ans2 = plusTwoNumbers($c);

echo $ans1.'<br>';
echo $ans2;
?>
この例では$twoの値にデフォルト値を設定しています。
引数をひとつしか渡していませんが、デフォルトの値があるので関数は機能します。
結果は以下の通りです。
「$a」に代入されていた「5」と「$two」に設定されたデフォルト値「10」が足され、
「15」が表示されています。下も同じく「$c」と「10」の合計で「13」です。



この場合、デフォルトの数値が関数内の処理に使用されましたが、
引数をこれまで通りふたつ引き渡すと、デフォルトではなく指定した値を
使用してくれます。
<?php
function plusTwoNumbers($one,$two=10){
    $ans = $one + $two;
    return $ans;
}

$a = 5;
$b = 8;
$c = 3;
$d = 7;

$ans1 = plusTwoNumbers($a,$b);
$ans2 = plusTwoNumbers($c,$d);

echo $ans1.'<br>';
echo $ans2;
?>


作る関数に何をさせるかにもよりますが、
使い分けることでさらに幅が広がりそうですね。

1 件のコメント:

Unknown さんのコメント...

It started off around 1984 for a aeroplanes air travel out of Paris, france , so that you can London, uk. Hermes' leader Jean-Louis Dumas appeared to be perched adjacent to fake rolex a celebrity Nara Birkin. When the woman appeared to be adding the girl's designer purse while in the expenses vehicle, most of the belongings all of the sudden lost his balance to your floors plus kept a celebrity really upset. Dumas started to rolex replica uk enable the girl's purchase all of the items including a dialog ensued. The woman in that case started to criticize about precisely how the woman appeared to be ineffective to see a saturday travelling bag that is proper so that you can the girl's noticing. Just after its limited face as well as uncovering with the girl's fake rolex blatant dislike for any present-day range saturday purses and handbags, Dumas resolved to brew a creator handbags for her that is based on the Haut Courroies, your style and design by way of Hermes out of gucci outlet within the move of your a single. This is certainly where popularity started off. After this 1st gift idea came out your lust for your creator handbags this obtained under no circumstances ended up found in advance of. Gals out of fake patek philippe everywhere ended up being swooning along at the pretty reference to it has the term. Fashionistas ended up being ready so that you can get in touch with a just about absolutely tailor-made designer purse their own.

コメントを投稿