LoginSignup
1
0

More than 1 year has passed since last update.

PHP returnで戻り値を返す

Posted at

returnによって返される戻り値について下記の点を常に意識できるように備忘録として。
returnが出来ること: 処理結果を関数に戻すことができる。
これによりreturnによって返された関数の処理結果を使いまわすことができる。(変数に代入して他の関数の引数として使う等。)

returnがされた時に起こること: 関数の処理はreturnがされた時点で終了する。
例えば下記のような関数function convert()ではreturn①の時点でこの関数の処理は終了となるため、return②は発生しない。(ダブらない。)

<?php
function convert(string $datetime)  
    $unix = strtotime($datetime);
    $now = time();
    $diff_sec = $now - $unix;

    if ($diff_sec < 60){
        $time = $diff_sec;
        $unit = '秒前';
    }else{
        if (date('Y') !== date('Y', $unix)){  
            $time =date('Y年n月j日',$unix);
        }else{
            $time = date('n月j日',$unix);
        }
        return $time; //return①
    }

    return(int)$time.$unit; //return②
} 
?>
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0