LoginSignup
3
3

More than 5 years have passed since last update.

配列の中身が参照だったときは強制参照渡しにはならない?

Last updated at Posted at 2015-04-22

概要

phpのバージョンを上げるときに5.3で禁止された強制参照渡しに関して少し気になることがあったのでメモ

強制参照渡しとは

php5.2までは関数側で参照を受け取っていなくても呼び出し時に強制的に参照を渡すことが出来た

function refTest($a)
{
    $a = 'hoge';
}

$b = '';

refTest(&$b);

var_dump($b); // string(4) "hoge"

これはphp5.3以降で

Fatal error: Call-time pass-by-reference has been removed

というエラーが出るようになった

要素に参照が含まれる配列だとエラーは出ない

どうやら関数に渡すときに&さえついていなければ何も言われないようで、以下のコードはphp5.5.20で普通に動く

<?php
function refTest($a)
{
    $a[0] = 'hoge';
}

$b = '';

$c = array(&$b);

refTest($c);

var_dump($c);
// array(1) {
//   [0]=>
//   &string(4) "hoge"
// }

そのうちこれも動かなくなる気はするのでなんにせよあんまり変なコードは書かないほうがいいですね

3
3
1

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
3