using $array1 = $array2 in PHP5 as if array is an object?
am 27.09.2007 22:54:59 von Summercoolness
I wonder in PHP5, can we use
$array1 = $array2 as if it is a class?
i think right now, the whole array is copied (by key and value)...
and i want to assign by reference but NOT in the alias sense.
in other world, i want to say
$array1 =& $array2;
$array2 = range(1, 3);
and I don't want $array1 to change, just like any other objects in
PHP5.
Re: using $array1 = $array2 in PHP5 as if array is an object?
am 27.09.2007 23:10:32 von gosha bine
Summercool wrote:
> I wonder in PHP5, can we use
>
> $array1 = $array2 as if it is a class?
>
> i think right now, the whole array is copied (by key and value)...
Correct. Arrays, like everything else, are assigned by copy, however php
implements lazy copying, that is, no bytes are physically moved until
you modify one of the copies.
$a1 = array(1, 2, 3);
$a2 = $a1; // no copying
$a2[0] = 9; // copy $a1 to $a2 and change $a2
>
> and i want to assign by reference but NOT in the alias sense.
>
> in other world, i want to say
>
> $array1 =& $array2;
> $array2 = range(1, 3);
>
> and I don't want $array1 to change, just like any other objects in
> PHP5.
>
Wrap them in objects.
//
$a1 = new stdclass;
$a1->a = array(1, 2, 3);
$a2 = $a1;
$a1->a[0] = 123;
echo $a2->a[0]; // $a1->a and $a2->a are the same
$a2 = 'foo';
var_dump($a1); // $a1 and $a2 are NOT the same
//
--
gosha bine
extended php parser ~ http://code.google.com/p/pihipi
blok ~ http://www.tagarga.com/blok
Re: using $array1 = $array2 in PHP5 as if array is an object?
am 27.09.2007 23:10:50 von Steve
"Summercool" wrote in message
news:1190926499.884760.217880@w3g2000hsg.googlegroups.com...
>I wonder in PHP5, can we use
>
> $array1 = $array2 as if it is a class?
>
> i think right now, the whole array is copied (by key and value)...
>
> and i want to assign by reference but NOT in the alias sense.
>
> in other world, i want to say
>
> $array1 =& $array2;
> $array2 = range(1, 3);
>
> and I don't want $array1 to change, just like any other objects in
> PHP5.
not sure i follow. the above code will produce *exactly* what you said you
don't want to. have you answered your own question by writing the 8 lines of
code it would take?
$array1 = $array2;
$array2 = range(1, 3);
echo ' copy ' . $array1 . '
';
unset($array1);
unset($array2);
$array1 = &$array2;
$array2 = range(1, 3);
echo ' reference ' . $array1 . '
';
that's all you get in any version of php currently. you get a copy of data
at a new address, or a pointer to an address where the data can be found
(c++ explanation...i know what aliasing is in php...long discussion on that
this week ;^)
what behavior are you wanting that the first echo in the example doesn't
provide? describe this 'reference'.