0

I have a php class like

class fiber {
   public $name
}
$array = array('1','2','3');

i need to create three object for the class fiber

i tried the following

foreach($array as $counts) {
   $obj = new fiber();
}

but its not working how to create three objects for a class using foreach

3
  • By the way, having an array of 1,2,3 might be a "code smell".. It's certainly not necessary in order to loop through and create objects, as you could just as soon use a for loop where $i<2 or $i<$length etc Commented Dec 19, 2013 at 7:54
  • @m59 while I don't disagree, you can't be too critical when it's even popularized in the PHP docs (first example) itself :/ - maybe they are doing something internally to optimize it? Commented Dec 19, 2013 at 8:01
  • @Emissary oh yeah! no criticism meant! I said it "might" be. There might be a great reason for it. I just wanted the OP to know some options in case it helped. Commented Dec 19, 2013 at 8:04

3 Answers 3

3

You're overwriting $obj each iteration. Instead, do this:

$myArray = array();

foreach($array as $counts) {
   array_push($myArray, new fiber());
}

Now you can access each fiber with $myArray[0] etc.

Here's a more complete and generic example (note the use of [] isn't supported before php 5.4).

class Fiber {
  private $x;
  public function __construct($x) {
    $this->x = $x;
  }
  public function getX() {
    return $this->x;
  }
}

$x = [1,2,3];

$Fibers = [];

foreach($x as $v) {
  $Fibers[]= new Fiber($v);
}

echo $Fibers[0]->getX(); //1
echo $Fibers[1]->getX(); //2
echo $Fibers[2]->getX(); //3

I really prefer $array[]= 'value' over array_push($array, 'value');

Sign up to request clarification or add additional context in comments.

2 Comments

@ChenAsraf good call. I write a lot of js also...so easy to write one in the other :)
It's all good, I was fixing it and deleting the comment when I saw you fixed it yourself. It's a common mistake ;)
1

This way you'd replace your current array values with new fiber class objects:

$array = array('1','2','3');

foreach($array as &$val) {
   $val = new fiber();
}

Or you can skip the part where you fill the array and do the following:

$array = array();

for ($i = 0; $i < 3; $i++)
    $array[$i] = new fiber();

Comments

-1

You could do it like this:

$index = 0;
foreach($array as $counts) {
   ${"obj$index"} = new fiber();
   $index++;
}

And you will have three objects $obj0, $obj1, $obj2.

1 Comment

Is this really a good way to use variables? Why number variables when you can use arrays? It's much better to be able to control and be able to get the size of the array. You can't do that with variable variables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.