Twitter iPhone pliant OnePlus 11 PS5 Disney+ Orange Livebox Windows 11

Probleme : array de references

3 réponses
Avatar
Zouplaz
Bonjour, j'ai un problème que je n'arrive pas à résoudre (j'ai monté
quelques lignes de code pour reproduire le phénomène) :

class test
{
var $ID;
}

$objets = array();
for($i=0;$i<5;$i++)
{
$obj = new test();
$ID = "ID$i";
$objets[$ID] = &$obj;
$obj->ID = $ID;
}

foreach($objets as $ID => $obj)
echo "IDarr:$ID - IDobj:" . $obj->$ID . "<br/>";
die();


L'éxecution du code affiche :
IDarr:ID0 - IDobj:
IDarr:ID1 - IDobj:
IDarr:ID2 - IDobj:
IDarr:ID3 - IDobj:
IDarr:ID4 - IDobj:

Ce qui signifie que quelque chose ne tourne pas rond ici :
$objets[$ID] = &$obj;


Et je ne vois pas quel problème peut bien se poser...
Je crée une instance et je stocke une référence de cette instance dans un
tableau, c'est con comme la lune.


Quelqu'un a une explication ?


Merci d'avance

3 réponses

Avatar
Cleo
foreach($objets as $ID => $obj)
echo "IDarr:$ID - IDobj:" . $obj->$ID . "<br/>";
die();


Il vaudrait mieux écrire :
echo "IDarr:$ID - IDobj:" . $obj->ID . "<br/>"
;) ...


Cependant plusieurs autres problèmes persistent mais n'affectent pas ton
traitement:

1- La ligne $obj = new test() devrait être remplacée par $obj =& new test();
car l'opérateur new crée un objet qui est cloné par l'opérateur
2- Attention sur la ligne foreach($objets as $ID => $obj), $obj est un clone
de $objets[$ID]
il vaudrait mieux écrire:
foreach($object as $ID => $dont_use_me) echo $object[$ID]->ID;
ou quelque chose dans le genre ...

--
Cléo.

Avatar
penthee
Zouplaz wrote:
Bonjour,
Bonjour,


j'ai un problème que je n'arrive pas à résoudre (j'ai monté
quelques lignes de code pour reproduire le phénomène) :

class test
{
var $ID;
}

$objets = array();
for($i=0;$i<5;$i++)
{
$obj = new test();
$ID = "ID$i";
$objets[$ID] = &$obj;
$obj->ID = $ID;
}

foreach($objets as $ID => $obj)
echo "IDarr:$ID - IDobj:" . $obj->$ID . "<br/>";
die();


L'éxecution du code affiche :
IDarr:ID0 - IDobj:
IDarr:ID1 - IDobj:
IDarr:ID2 - IDobj:
IDarr:ID3 - IDobj:
IDarr:ID4 - IDobj:



ceci fonctionne chez moi :

class test
{
var $ID;
}
$objets = array();
for($i=0;$i<5;$i++)
{
$obj = new test();
$ID = "ID$i";
$obj->ID = $ID;
$objets[$ID] = $obj;
}

foreach($objets as $ID => $obj)
echo "IDarr:$ID - IDobj:" . $obj->ID . "<br/>";
die();

sortie :
IDarr:ID0 - IDobj:ID0
IDarr:ID1 - IDobj:ID1
IDarr:ID2 - IDobj:ID2
IDarr:ID3 - IDobj:ID3
IDarr:ID4 - IDobj:ID4

Merci d'avance
De rien. Si ça peut aider...

pierre

Avatar
Marc

Quelqu'un a une explication ?



voila qq chose qui fonctionne :

<?php

class test
{
var $ID;
}

$objets = array();
for($i=0;$i<5;$i++)
{
$obj = &new test();
$ID = "ID$i";
$objets[$ID] = &$obj;
$obj->ID = $ID;
}

foreach($objets as $ID => $obj_copy)
echo "IDarr:$ID - IDobj:" . $obj_copy->ID . "n";

die();

?>