48
40

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PHPで複数の値をreturnする[備忘]

Last updated at Posted at 2019-03-07

やりたい事

  • 複数の値を一回のreturnにまとめたい

環境

  • PHP 7.2.6
  • CakePHP 3.6.13

サンプルコード

  • 生のPHPコードの場合
private function samples()
{
    $fruits1 = 'apple';
    $fruits2 = 'banana';

    return [$fruits1, $fruits2]; // もしくは、array($fruits1, $fruits2);
}

list($fruits1, $fruits2) = $this->samples();

echo $fruits1; // => apple
echo $fruits2; // => banana

解説

  • samplesアクション

    • $fruits1と**$fruits2**を定義
    • returnする時に配列にする
  • list関数

list — 配列と同様の形式で、複数の変数への代入を行う
引用元:http://php.net/manual/ja/function.list.php

- list関数を使用し、**samples**アクションの返り値を受け取る

所感

  • 1回のreturnで済む事は気持ちいい
  • functionに切り出す程でもないけど、2つの値をそれぞれ呼び出し元に返したい場合の解消手段になり得る
  • 見慣れないせいか、直感的なコードの可読性はそこまで高くない?
  • 世間一般的に、こういう手法を使うのだろうか?
48
40
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
48
40

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?