3
1

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 1 year has passed since last update.

php: 参照渡し

Posted at

引数の変数に&を付けるとリファレンス渡しになる。
グローバル変数のように扱えるが可読性は悪くなる。

値に参照

function increment(&$var)
{
    $var++;
}

$a = 0;
increment($a);
echo $a; // 1

increment($a);
echo $a; //2

また関数をリファレンス渡しすることもできる

function increment(&$var)
{
    $var++;
    return $var;
}

function &reference()
{
    $a = 0;
    return $a;
}

$a = increment(reference());
echo $a; // 1

配列やオブジェクトの参照

少し面白い。
配列は参照できないが、objectは参照渡しできるみたい。

function increment($arr)
{
    foreach ($arr as &$i) {
        $i++;
    }
}

$arr = [1,2,3,4,5];
increment($arr);
print_r($arr); // [1,2,3,4,5]

$obj = (object)$arr;
increment($obj);
print_r($obj); // [2,3,4,5,6]
3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?