関数
PHP
function showAD()
{
echo '--------------' . PHP_EOL;
}
showAD();
echo 'Tom is great!' . PHP_EOL;
echo 'Bob is great!' . PHP_EOL;
showAD();
echo 'Steve is great!' . PHP_EOL;
echo 'Bob is great!' . PHP_EOL;
showAD();
# 繰り返し、何度も使うものには便利
引数
PHP
function showAd($message = Ad) //仮引数
{
echo '----------' . PHP_EOL;
echo '--- ' . $message . ' ---' . PHP_EOL;
echo '----------' . PHP_EOL;
}
showAd("Header Ad"); //実引数
echo 'Tom is great!' . PHP_EOL;
echo 'Bob is great!' . PHP_EOL;
showAd("AD");
echo 'Steve is great!' . PHP_EOL;
echo 'Bob is great!' . PHP_EOL;
showAd("Footer Ad");
# 繰り返し、何度も使う際、内容が変わる時に便利
無名関数
PHP
$sum = function ($a, $b, $c){ //無名関数
return $a + $b + $c;
};
echo $sum(100, 300, 500) . PHP_EOL;
# 関数自体を値にできる
# 最後に「;」が必要になる
条件演算子
PHP
function sum($a, $b, $c)
{
$total = $a + $b + $c;
if($total < 0){
return 0;
}else{
return $total;
}
}
echo sum(100, 300, 500) . PHP_EOL;
これを条件演算子を使用すると、、、
PHP
function sum($a, $b, $c)
{
$total = $a + $b + $c;
return $total < 0 ? 0 : $total;
}
echo sum(100, 300, 500) . PHP_EOL;
# 条件 ? 値 値 と書く。
# trueなら左側、fulseなら右側の値になる。
引数の型を指定
PHP
declare(strict_types=1);
# 強い型指定の時に入れる文
function showInfo(string $name,int $score):void
{
echo $name . ': ' . $score . PHP_EOL;
}
showInfo('Taguchi','4');
# stringやintを型指定できる!
nullの場合
PHP
declare(strict_types=1);
function getAward(int $score): ?string
{
return $score >= 100 ? 'Gold Medal' : null;
}
echo getAward(150) . PHP_EOL;
echo getAward(50) . PHP_EOL;
// stringの前に「?」を付けることで、
// nullか?それ以外か?を返すことができる。
// 単純にstringだけの場合、100点未満だとエラーになってしまう。
配列の取り出し
PHP
$scores = [
'first' => 90,
'second' => 40,
'third' => 100,
];
foreach($scores as $score){
echo $score . PHP_EOL;
}
foreach($scores as $key => $score){
echo $key . PHP_EOL;
}
// foreach文で値やキーを取り出すことができる
PHP
print_r(配列名)
# 配列の中身の確認できる
# 結構、使いそう!
配列の取り出し
PHP
<?php
$moreScores = [
55,
72,
'perfect',
[90, 42, 88],
];
$scores = [
90,
40,
...$moreScores,
100,
];
// print_r($scores);
echo $scores[5][2] . PHP_EOL;
# 配列の中に配列を入れると、数字ではなくarry扱いになってしまう。
# そのため、「...」を付けることで別配列の中の数字を扱える
可変長引数
PHP
# 通常なら、function sum($a, $b, $c)
# これを、幾つでも数字を増やすために配列型にすると
# function sum(...$numbers) となる。
# この配列はforeachで取り出せるので、
function sum(...$numbers)
{
$totals = 0;
foreach($numbers as $number){
$total += $number;
}
return $total;
}
each sum(1,3,5) . PHP_EOL;