How to put new elements in an object array in php, I made some code but it is not working. Here is my code:
<?php
class DNA{
private $RSID;
private $CHROMOSOME;
public function setRSID($RSID){
return $this->RSID = $RSID;
}
public function setCHROMOSOME($CHROMOSOME){
return $this->CHROMOSOME = $CHROMOSOME;
}
public function getRSID(){
return $this->RSID;
}
public function getCHROMOSOME(){
return $this->CHROMOSOME;
}
}
$dna1[] = new DNA;
$dna1[0]->setRSID(1);
$dna1[0]->setCHROMOSOME(2);
$dna1[1]->setRSID(5);
$dna1[1]->setCHROMOSOME(3);
$dna1[2]->setRSID(7);
$dna1[2]->setCHROMOSOME(0);
?>
I do not know the correct syntax, I tried to find in the google, but I am not found a good solution. Someone can help me?
CodePudding user response:
Each time you run new DNA
creates a single object, so if you want to have multiple objects you need to call it multiple times.
In your case, you're just running it once: $dna1[] = new DNA;
creates a single object, and adds it to an array.
To create three objects, you could do this:
// First create an empty array
$dna1 = [];
// Now add objects to it one by one
$dna1[0] = new DNA;
$dna1[0]->setRSID(1);
$dna1[0]->setCHROMOSOME(2);
$dna1[1] = new DNA;
$dna1[1]->setRSID(5);
$dna1[1]->setCHROMOSOME(3);
$dna1[2] = new DNA;
$dna1[2]->setRSID(7);
$dna1[2]->setCHROMOSOME(0);
CodePudding user response:
Hy you can try with associative array
php.net/manual/en/language.types.array.php
The result is like this,
$dna = new DNA();
$dna_array[0]['rsid'] = $dna->setRSID(1);
$dna_array[0]['chromsome'] = $dna->setCHROMOSOME(2);
$dna_array[1]['rsid'] = $dna->setRSID(5);
$dna_array[1]['chromsome'] = $dna->setCHROMOSOME(3);
$dna_array[2]['rsid'] = $dna->setRSID(7);
$dna_array[2]['chromsome'] = $dna->setCHROMOSOME(0);
var_dump($dna_array);
var_dump($dna_array[0]);
var_dump($dna_array[1]);
var_dump($dna_array[2]);
var_dump($dna_array);
var_dump($dna_array[0]['rsid']);
var_dump($dna_array[0]['chromsome']);