lys916
lys916

Reputation: 317

How do i turn an array of strings into objects?

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.

Upvotes: 0

Views: 39

Answers (2)

Premalatha
Premalatha

Reputation: 166

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 :)

Upvotes: 0

eol
eol

Reputation: 24555

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

Upvotes: 1

Related Questions