Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

 
Reply to this topicStart new topic
> Klonowane obiekty w tablicy.
tmka
post
Post #1





Grupa: Zarejestrowani
Postów: 27
Pomógł: 9
Dołączył: 9.02.2009

Ostrzeżenie: (0%)
-----


Witam,
mam taki kod:
CODE
$_emptyItem = new stdClass();
$_emptyItem->title = '';
$_emptyItem->nr = 0;
$_emptyItem->price = 0;
$_emptyItem->status->no_item = 0;


$itm1 = clone $_emptyItem;
$itm1->status->no_item = 14;
$itm1->nr =4;
var_dump($itm1);
$lista[] = $itm1;

$itm2 = clone $_emptyItem;
$itm2->status->no_item = 434;
$itm2->nr =866;
var_dump($itm2);
$lista[] = $itm2;

$itm3 = clone $_emptyItem;
$itm3->status->no_item = 345;
$itm3->nr =123432;
var_dump($itm3);
$lista[] = $itm3;

var_dump($lista);


skrypt wyswietla mi coś takiego:
CODE
object(stdClass)#3 (4) {
["title"]=>
string(0) ""
["nr"]=>
int(4)
["price"]=>
int(0)
["status"]=>
object(stdClass)#2 (1) {
["no_item"]=>
int(14)
}
}
object(stdClass)#4 (4) {
["title"]=>
string(0) ""
["nr"]=>
int(866)
["price"]=>
int(0)
["status"]=>
object(stdClass)#2 (1) {
["no_item"]=>
int(434)
}
}
object(stdClass)#5 (4) {
["title"]=>
string(0) ""
["nr"]=>
int(123432)
["price"]=>
int(0)
["status"]=>
object(stdClass)#2 (1) {
["no_item"]=>
int(345)
}
}
array(3) {
[0]=>
object(stdClass)#3 (4) {
["title"]=>
string(0) ""
["nr"]=>
int(4)
["price"]=>
int(0)
["status"]=>
object(stdClass)#2 (1) {
["no_item"]=>
int(345)
}
}
[1]=>
object(stdClass)#4 (4) {
["title"]=>
string(0) ""
["nr"]=>
int(866)
["price"]=>
int(0)
["status"]=>
object(stdClass)#2 (1) {
["no_item"]=>
int(345)
}
}
[2]=>
object(stdClass)#5 (4) {
["title"]=>
string(0) ""
["nr"]=>
int(123432)
["price"]=>
int(0)
["status"]=>
object(stdClass)#2 (1) {
["no_item"]=>
int(345)
}
}
}


W sumie obiekty klonują się prawidłowo, problem pojawia się po wrzuceniu ich do tablicy. Nie wiem dlaczego, ale pole $..->status->no_item we wszystkich obiektach w tablicy zawiera wartość ostatnio wrzuconego pola, co widać na załączonym listingu. Może ktoś wie dlaczego tak jest i czy można jakoś temu zaradzić.

Pozdrawiam.
Go to the top of the page
+Quote Post
dr_bonzo
post
Post #2





Grupa: Przyjaciele php.pl
Postów: 5 724
Pomógł: 259
Dołączył: 13.04.2004
Skąd: N/A

Ostrzeżenie: (0%)
-----


Bo robisz plytkie clone (tzn samo sie takie robi i tak wlasnie ma byc).
"status" w obu obiektach $item to ten sam obiekt.
Poczytaj o metodzie __clone() i clone w manualu jak zrobic deep clone - czyli sklonowac tez status.


--------------------
Nie lubię jednorożców.
Go to the top of the page
+Quote Post

Reply to this topicStart new topic
1 Użytkowników czyta ten temat (1 Gości i 0 Anonimowych użytkowników)
0 Zarejestrowanych:

 



RSS Aktualny czas: 19.08.2025 - 06:49