filemonczyk filemonczyk - 1 month ago 5
PHP Question

creating objects using array in php

I have array of data , and base of that I would like to create as many objects as the array have:

I'm trying to do it with foreach loop, but cant crack it.

foreach($file->data as $item){
$entity = new MappedEntity($file,$counter++);
}


it's working but for example array length =5 , It's overriding the value 5 times and as result I'm having one object with values from fifth record, and I would like to create 5 objects with corresponding properties.

Im total newbie to PHP , any suggestions?

Answer

This is quite a weird way to behave, but before further knowledge, you can create 5 instances of your class like this:

$i = 1;

foreach ($file->data as $item) {
  ${"entity_" . $i} = new MappedEntity($file, $counter++);
  $i++;
}

//now you have class instances in variables $entity_1, $entity_2 etc...

Or you can store instances to array like this ( preferred way to do this ):

$arr = [];

foreach ($file->data as $item) {
  $arr[] = new MappedEntity($file, $counter++);
}

// now you have array with 5 class instances and you can access them with $arr[0], $arr[1] etc...
Comments