开发者

PHP::Reference or copy (case inside)?

Please help me to prove about the case if variable reference or copy.

Case1 - $arr copy or reference?:

class Ex1{
 public static $var1=array(10=>'work', 20=>'home'); 
}
$arr=Ex1::$var1;

Case2 - $arr copy or reference?:

 class Ex1{
     protected static $var1=array(10=>'work', 20=>'home'); 
     p开发者_Go百科ublic static function getArr(){
      return self::$var1;
       }
    }
    $arr=Ex1::getArr();

Thanks, Yosef


By my reckoning, it should be a copy.

class Ex1{
    public static $var1=array(10=>'work', 20=>'home');
}

$arr=Ex1::$var1;

var_dump($arr);

$arr[15] = 'play';

var_dump($arr);

$arr2=Ex1::$var1;

var_dump($arr2);

Ex1::$var1 = array(10=>'work', 15=>'asylum', 20=>'home');

$arr3=Ex1::$var1;

var_dump($arr3);

var_dump($arr2);

gives

array
  10 => string 'work' (length=4)
  20 => string 'home' (length=4)

array
  10 => string 'work' (length=4)
  20 => string 'home' (length=4)
  15 => string 'play' (length=4)

array
  10 => string 'work' (length=4)
  20 => string 'home' (length=4)

array
  10 => string 'work' (length=4)
  15 => string 'asylum' (length=6)
  20 => string 'home' (length=4)

array
  10 => string 'work' (length=4)
  20 => string 'home' (length=4)


Both copy. Only objects are transmitted by reference by default.


Modify $arr and then var_dump(Ex1::getArr()); and you'll see if it was a copy or a reference.

edit: didn't see Ex1::var1 was protected


It is going to be a copy, test it like:

$arr=Ex1::$var1;
$arr['omg'] = 'lol';
var_dump($arr);
var_dump(Ex1::$var1);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜