0

I have a class Team{}. I have an array of strings $teams = array('team1', 'team2', 'team3'). I want to loop through the array and create an object with each string as the object name.

class Team{}

$teams = array('team1', 'team2', 'team3');

foreach ($teams as $team) {
    $team = new Team();
}

So $team1, $team2 and $team3 becomes object.

Thanks for your help.

1
  • 1
    Either use the key to access the array and assign the object or use the value by reference. Commented Jul 7, 2016 at 6:13

2 Answers 2

1

Assuming that Team has a property "name" just do it like this:

class Team {

  private $yourPropertyForName;

  public function __construct($name) {
    $this->yourPropertyForName = $name;
    //initialise the rest of your properties
  }
}

$teamList = [];    
$teams = array('team1', 'team2', 'team3');

foreach ($teams as $teamName) {
   array_push($teamList, new Team($teamName));
}
//teamList now contains the three Team objects
Sign up to request clarification or add additional context in comments.

2 Comments

My original code already has multiple properties for the Team class such as name, location etc. Will this still work?
Yes just change the constructor accordingly, see my updated answer
0
You can use this just another "$" symbol for the team variable would give what you are expecting.

<?php
    Class Team{}    
    $teams = array('team1', 'team2', 'team3');    
    foreach ($teams as $team) {
       $$team = new Team();
    }
    var_dump($team1);
    var_dump($team2);
    var_dump($team3);    
?>

Which outputs like object(Team)#1 (0) { } object(Team)#2 (0) { } object(Team)#3 (0) { }

as you are expecting :)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.