开发者

References and Arrays in PHP

I'm new to programming in general and references in particular. I want to manipulate individual objects in an array by开发者_高级运维 reference, so that I'm not working on mere copies of the objects I wanted to stick into the array. My question is how to do that.

For example, suppose I have these lines of code:

$obj0 = blah;
$obj1 = blah;
$obj2 = blah;
$myArray = array($obj0, $obj1, $obj2);

When I now access and modify $myArray[1], will this be the same as modifying $obj1? Or would I have to be modifying &$myArray[1] instead?


As it stands, no you will not alter the initial variables.

If you wish to do it by reference, you should put those ampersands when you setup the array like so.

$myArray = array(&$obj0, &$obj1, &$obj2);

Code:

    $a = "cat"; $a1 = "cat";
    $b = "dog"; $b1 = "dog";
    $arrRef = array(&$a, &$b); $arrCopy = array($a, $b);
    $arrRef[0] .= "food"; $arrCopy[0] .= "food";
    $arrRef[1] .= "house"; $arrCopy[1] .= "house";
    echo "a: $a   b: $b <br />";
    echo "a1: $a1   b1: $b1 <br />";

Output:

a: catfood b: doghouse
a1: cat b1: dog 


No, modifying $myArray[1] is not the same as modifying $obj1. However, if you are operating on the object that they both point to, that object will be changed.

In other words:

// Does not affect $obj1, but it does affect $obj1->foo
$myArray[1]->foo = "bar";

// Does not affect $obj1, which continues to point to the same object
$myArray[1] = null; 


In PHP5 objects are called "by reference" by default so there is no need to prepend $myArray[1] with '&'.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜