PHPのお勉強!

PHP TOP

リファレンスが行うことは何ですか?

リファレンスを使う基本操作には三通りあります。 リファレンスの代入リファレンス渡し、 そして リファレンスを返すことです。 この節では、これらの操作に関する基本的な解説をします。 そして、詳細な説明へのリンクを示します。

リファレンスの代入

まず最初の操作です。PHP のリファレンスを使うと、 ふたつの変数が同じ内容を指すようにできます。 次の例を考えてみましょう。

<?php

$a
=& $b;

?>
この場合、$a$b は同じ内容を指します。

注意:

ここで、$a$b は完全に 同じで、$a$b を 指しているわけではなく、その逆でもありません。$a$b は同じ場所を指しているのです。

注意:

未定義の変数のリファレンスに対して代入したり 渡したり返したりすると、そこで変数が作成されます。

例1 未定義の変数のリファレンスの使用

<?php

function foo(&$var) {}

foo($a); // $a が作成され、null が代入されます

$b = array();
foo($b['b']);
var_dump(array_key_exists('b', $b)); // bool(true)

$c = new stdClass();
foo($c->d);
var_dump(property_exists($c, 'd')); // bool(true)

?>

リファレンスを返す関数でも 同じ構文が使用可能です

<?php

$foo
=& find_var($bar);

?>

リファレンスを返さない関数で、同じ構文を使うとエラーになります。 new 演算子の結果に対して同じ構文を使った場合もエラーになります。 オブジェクトはポインタで渡されますが、 これはリファレンスとは異なります。 詳細な情報は オブジェクトと参照 にあります。

警告

関数の内部で global 宣言された変数にリファレンスを 代入すると、そのリファレンスは関数の内部でのみ参照可能となります。 これを避けるには、$GLOBALS 配列を使用します。

例2 関数内でのグローバル変数の参照

<?php

$var1
= "Example variable";
$var2 = "";

function
global_references($use_globals)
{
global
$var1, $var2;

if (!
$use_globals) {
$var2 =& $var1; // 関数の内部でのみ参照可能
} else {
$GLOBALS["var2"] =& $var1; // 関数の外部でも参照可能
}
}

global_references(false);
echo
"var2 の値は '$var2'\n"; // var2 の値は ''

global_references(true);
echo
"var2 の値は '$var2'\n"; // var2 の値は 'Example variable'

?>
global $var; は、$var =& $GLOBALS['var']; の短縮版だと考えてください。 これにより、他のリファレンスを $var に代入し、 ローカル変数のリファレンスのみを変更します。

注意:

foreach ステートメントの内部でリファレンス変数に値を代入すると、リファレンスも変更されます。

例3 リファレンスと foreach ステートメント

<?php

$ref
= 0;
$row =& $ref;

foreach (array(
1, 2, 3) as $row) {
// 何かを実行します
}

echo
$ref; // 3 - 配列の最後の要素

?>

厳密にリファレンスでの代入をしなくても、 array() で作成した式は、配列の要素の先頭に & を追加したのと同じような動作をします。たとえば、次のようになります。

<?php

$a
= 1;
$b = array(2, 3);

$arr = array(&$a, &$b[0], &$b[1]);
$arr[0]++;
$arr[1]++;
$arr[2]++;
/* $a == 2, $b == array(3, 4); */

?>

しかし、配列の内部のリファレンスは危険もあるということに気をつけましょう。 通常の (リファレンスではない) 代入の右辺にリファレンスを使っても 左辺がリファレンスに変わることはありませんが、配列の内部のリファレンスは通常の代入においても維持されます。 これは、関数をコールする際に配列をリファレンスで渡すときも同じです。 たとえば、次のようになります。

<?php

/* スカラー変数への代入 */
$a = 1;
$b =& $a;
$c = $b;
$c = 7; // $c はリファレンスではないので $a や $b の値は変わりません

/* 配列変数への代入 */
$arr = array(1);
$a =& $arr[0]; // $a および $arr[0] は同じリファレンスセットになります
$arr2 = $arr; // これは、リファレンス代入ではありません!
$arr2[0]++;
/* $a == 2, $arr == array(2) */
/* $arr の内容は、たとえリファレンスでなくても変わります! */

?>
言い換えると、配列内のリファレンスの挙動はその要素ごとに決まるということです。 個々の要素のリファレンスに関する動きは、 配列コンテナがリファレンスであるかどうかとは独立しています。

リファレンス渡し

リファレンスの第 2 の使用法は、変数のリファレンス渡しです。この場合、 関数でローカル変数が作成され、コール側の変数が、それと同じ内容への リファレンスとなります。例を示します。

<?php

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

$a=5;
foo($a);

?>
この結果、$a は 6 となります。これは、関数 foo の中では、変数 $var$a と同じ内容を指しているためです。 より詳細な説明は、 リファレンス渡し を参照ください。

リファレンスによる戻り値

リファレンスの第 3 の使用法は、 リファレンスによる戻り値 です。

add a note

User Contributed Notes 23 notes

up
69
ladoo at gmx dot at
19 years ago
I ran into something when using an expanded version of the example of pbaltz at NO_SPAM dot cs dot NO_SPAM dot wisc dot edu below.
This could be somewhat confusing although it is perfectly clear if you have read the manual carfully. It makes the fact that references always point to the content of a variable perfectly clear (at least to me).

<?php
$a
= 1;
$c = 2;
$b =& $a; // $b points to 1
$a =& $c; // $a points now to 2, but $b still to 1;
echo $a, " ", $b;
// Output: 2 1
?>
up
3
dexant9t at gmail dot com
3 years ago
It matters if you are playing with a reference or with a value

Here we are working with values so working on a reference updates original variable too;

$a = 1;
$c = 22;

$b = & $a;
echo "$a, $b"; //Output: 1, 1

$b++;
echo "$a, $b";//Output: 2, 2 both values are updated

$b = 10;
echo "$a, $b";//Output: 10, 10 both values are updated

$b =$c; //This assigns value 2 to $b which also updates $a
echo "$a, $b";//Output: 22, 22

But, if instead of $b=$c you do
$b = &$c; //Only value of $b is updated, $a still points to 10, $b serves now reference to variable $c

echo "$a, $b"//Output: 10, 22
up
36
Hlavac
17 years ago
Watch out for this:

foreach ($somearray as &$i) {
// update some $i...
}
...
foreach ($somearray as $i) {
// last element of $somearray is mysteriously overwritten!
}

Problem is $i contians reference to last element of $somearray after the first foreach, and the second foreach happily assigns to it!
up
26
elrah [] polyptych [dot] com
13 years ago
It appears that references can have side-effects. Below are two examples. Both are simply copying one array to another. In the second example, a reference is made to a value in the first array before the copy. In the first example the value at index 0 points to two separate memory locations. In the second example, the value at index 0 points to the same memory location.

I won't say this is a bug, because I don't know what the designed behavior of PHP is, but I don't think ANY developers would expect this behavior, so look out.

An example of where this could cause problems is if you do an array copy in a script and expect on type of behavior, but then later add a reference to a value in the array earlier in the script, and then find that the array copy behavior has unexpectedly changed.

<?php
// Example one
$arr1 = array(1);
echo
"\nbefore:\n";
echo
"\$arr1[0] == {$arr1[0]}\n";
$arr2 = $arr1;
$arr2[0]++;
echo
"\nafter:\n";
echo
"\$arr1[0] == {$arr1[0]}\n";
echo
"\$arr2[0] == {$arr2[0]}\n";

// Example two
$arr3 = array(1);
$a =& $arr3[0];
echo
"\nbefore:\n";
echo
"\$a == $a\n";
echo
"\$arr3[0] == {$arr3[0]}\n";
$arr4 = $arr3;
$arr4[0]++;
echo
"\nafter:\n";
echo
"\$a == $a\n";
echo
"\$arr3[0] == {$arr3[0]}\n";
echo
"\$arr4[0] == {$arr4[0]}\n";
?>
up
11
amp at gmx dot info
17 years ago
Something that might not be obvious on the first look:
If you want to cycle through an array with references, you must not use a simple value assigning foreach control structure. You have to use an extended key-value assigning foreach or a for control structure.

A simple value assigning foreach control structure produces a copy of an object or value. The following code

$v1=0;
$arrV=array(&$v1,&$v1);
foreach ($arrV as $v)
{
$v1++;
echo $v."\n";
}

yields

0
1

which means $v in foreach is not a reference to $v1 but a copy of the object the actual element in the array was referencing to.

The codes

$v1=0;
$arrV=array(&$v1,&$v1);
foreach ($arrV as $k=>$v)
{
$v1++;
echo $arrV[$k]."\n";
}

and

$v1=0;
$arrV=array(&$v1,&$v1);
$c=count($arrV);
for ($i=0; $i<$c;$i++)
{
$v1++;
echo $arrV[$i]."\n";
}

both yield

1
2

and therefor cycle through the original objects (both $v1), which is, in terms of our aim, what we have been looking for.

(tested with php 4.1.3)
up
4
Anonymous
9 years ago
to reply to ' elrah [] polyptych [dot] com ', one thing to keep in mind is that array (or similar large data holders) are by default passed by reference. So the behaviour is not side effect. And for array copy and passing array inside function always done by 'pass by reference'...
up
9
nay at woodcraftsrus dot com
13 years ago
in PHP you don't really need pointer anymore if you want to share an object across your program

<?php
class foo{
protected
$name;
function
__construct($str){
$this->name = $str;
}
function
__toString(){
return
'my name is "'. $this->name .'" and I live in "' . __CLASS__ . '".' . "\n";
}
function
setName($str){
$this->name = $str;
}
}

class
MasterOne{
protected
$foo;
function
__construct($f){
$this->foo = $f;
}
function
__toString(){
return
'Master: ' . __CLASS__ . ' | foo: ' . $this->foo . "\n";
}
function
setFooName($str){
$this->foo->setName( $str );
}
}

class
MasterTwo{
protected
$foo;
function
__construct($f){
$this->foo = $f;
}
function
__toString(){
return
'Master: ' . __CLASS__ . ' | foo: ' . $this->foo . "\n";
}
function
setFooName($str){
$this->foo->setName( $str );
}
}

$bar = new foo('bar');

print(
"\n");
print(
"Only Created \$bar and printing \$bar\n");
print(
$bar );

print(
"\n");
print(
"Now \$baz is referenced to \$bar and printing \$bar and \$baz\n");
$baz =& $bar;
print(
$bar );

print(
"\n");
print(
"Now Creating MasterOne and Two and passing \$bar to both constructors\n");
$m1 = new MasterOne( $bar );
$m2 = new MasterTwo( $bar );
print(
$m1 );
print(
$m2 );

print(
"\n");
print(
"Now changing value of \$bar and printing \$bar and \$baz\n");
$bar->setName('baz');
print(
$bar );
print(
$baz );

print(
"\n");
print(
"Now printing again MasterOne and Two\n");
print(
$m1 );
print(
$m2 );

print(
"\n");
print(
"Now changing MasterTwo's foo name and printing again MasterOne and Two\n");
$m2->setFooName( 'MasterTwo\'s Foo' );
print(
$m1 );
print(
$m2 );

print(
"Also printing \$bar and \$baz\n");
print(
$bar );
print(
$baz );
?>
up
5
charles at org oo dot com
17 years ago
points to post below me.
When you're doing the references with loops, you need to unset($var).

for example
<?php
foreach($var as &$value)
{
...
}
unset(
$value);
?>
up
4
Oddant
11 years ago
About the example on array references.
I think this should be written in the array chapter as well.
Indeed if you are new to programming language in some way, you should beware that arrays are pointers to a vector of Byte(s).

<?php $arr = array(1); ?>
$arr here contains a reference to which the array is located.
Writing :
<?php echo $arr[0]; ?>
dereferences the array to access its very first element.

Now something that you should also be aware of (even you are not new to programming languages) is that PHP use references to contains the different values of an array. And that makes sense because the type of the elements of a PHP array can be different.

Consider the following example :

<?php

$arr
= array(1, 'test');

$point_to_test =& $arr[1];

$new_ref = 'new';

$arr[1] =& $new_ref;

echo
$arr[1]; // echo 'new';
echo $point_to_test; // echo 'test' ! (still pointed somewhere in the memory)

?>
up
3
php.devel at homelinkcs dot com
20 years ago
In reply to lars at riisgaardribe dot dk,

When a variable is copied, a reference is used internally until the copy is modified. Therefore you shouldn't use references at all in your situation as it doesn't save any memory usage and increases the chance of logic bugs, as you discoved.
up
3
dovbysh at gmail dot com
17 years ago
Solution to post "php at hood dot id dot au 04-Mar-2007 10:56":

<?php
$a1
= array('a'=>'a');
$a2 = array('a'=>'b');

foreach (
$a1 as $k=>&$v)
$v = 'x';

echo
$a1['a']; // will echo x

unset($GLOBALS['v']);

foreach (
$a2 as $k=>$v)
{}

echo
$a1['a']; // will echo x

?>
up
4
Amaroq
14 years ago
I think a correction to my last post is in order.

When there is a constructor, the strange behavior mentioned in my last post doesn't occur. My guess is that php was treating reftest() as a constructor (maybe because it was the first function?) and running it upon instantiation.

<?php
class reftest
{
public
$a = 1;
public
$c = 1;

public function
__construct()
{
return
0;
}

public function
reftest()
{
$b =& $this->a;
$b++;
}

public function
reftest2()
{
$d =& $this->c;
$d++;
}
}

$reference = new reftest();

$reference->reftest();
$reference->reftest2();

echo
$reference->a; //Echoes 2.
echo $reference->c; //Echoes 2.
?>
up
2
akinaslan at gmail dot com
13 years ago
In this example class name is different from its first function and however there is no construction function. In the end as you guess "a" and "c" are equal. So if there is no construction function at same time class and its first function names are the same, "a" and "c" doesn't equal forever. In my opinion php doesn't seek any function for the construction as long as their names differ from each others.

<?php
class reftest_new
{
public
$a = 1;
public
$c = 1;

public function
reftest()
{
$b =& $this->a;
$b++;
}

public function
reftest2()
{
$d =& $this->c;
$d++;
}
}

$reference = new reftest_new();

$reference->reftest();
$reference->reftest2();

echo
$reference->a; //Echoes 2.
echo $reference->c; //Echoes 2.
?>
up
2
Amaroq
16 years ago
The order in which you reference your variables matters.

<?php
$a1
= "One";
$a2 = "Two";
$b1 = "Three";
$b2 = "Four";

$b1 =& $a1;
$a2 =& $b2;

echo
$a1; //Echoes "One"
echo $b1; //Echoes "One"

echo $a2; //Echoes "Four"
echo $b2; //Echoes "Four"
?>
up
2
Drewseph
16 years ago
If you set a variable before passing it to a function that takes a variable as a reference, it is much harder (if not impossible) to edit the variable within the function.

Example:
<?php
function foo(&$bar) {
$bar = "hello\n";
}

foo($unset);
echo(
$unset);
foo($set = "set\n");
echo(
$set);

?>

Output:
hello
set

It baffles me, but there you have it.
up
1
dnhuff at acm dot org
16 years ago
In reply to Drewseph using foo($a = 'set'); where $a is a reference formal parameter.

$a = 'set' is an expression. Expressions cannot be passed by reference, don't you just hate that, I do. If you turn on error reporting for E_NOTICE, you will be told about it.

Resolution: $a = 'set'; foo($a); this does what you want.