LoginSignup
5
2

More than 3 years have passed since last update.

参照渡しでのエラー「Only variables should be passed by reference」について

Posted at

最近コード書いてたら出くわしたエラーに関して忘備録として残しておきます。
間違えてる箇所がありましたら優しくご指摘お願いします。

「Only variables should be passed by reference」
ざっくりというと「参照渡しは変数しか使えませんよ〜」っていうエラーです。

下のコードのように、storeContactInfoの引数の中に直接「$id = null」を入れていたのですが、
このやり方ではダメっぽいです。

foreach ($infoList as $info) 
{
  // 登録処理
  $this->storeContactInfo($name, $id = null);
}

private function saveContactInfo(string $name, ?int &$id)
{
 (省略)
  // DBに登録
  $contact->save();
}

そのため、一旦変数に入れてあげて、その変数を引数で使うようにしてあげたら無事に解決しました。

foreach ($infoList as $info) {
  $id = null;
  // 登録処理
  $this->storeContactInfo($name, $id);
}

一見おかしくはなさそうなんですけど、saveContactInfo()側は参照渡しを要求しているのに、
呼び出し側で値渡ししているのが原因でおきてるそうです。

解決できたので、めでたしめでたし。

5
2
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
5
2