简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM