如何将字符串数组转换为对象?

时间:2016-07-07 06:12:44

标签: php arrays object

我有一个班级队员{}。 我有一系列字符串$ teams = array(' team1',' team2',' team3')。 我想遍历数组并创建一个对象,每个字符串作为对象名称。

class Team{}

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

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

所以$ team1,$ team2和$ team3成为对象。

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

假设团队有一个属性"name",就这样做:

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

答案 1 :(得分: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);    
?>

哪个输出像 object(Team)#1(0){} object(Team)#2(0){} object(Team)#3(0){}

正如您所料:)