2016-07-07 102 views
0

我有班级{}。 我有一个字符串数组$ team = array('team1','team2','team3')。 我想遍历数组并创建一个对象,每个字符串作为对象名称。如何将字符串数组转换为对象?

class Team{} 

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

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

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

感谢您的帮助。

+1

既可以使用密钥来访问所述阵列和分配对象或通过参考使用的值。 – Rizier123

回答

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 
+0

我原来的代码已经有了Team类的多个属性,比如名字,位置等等。这个问题仍然有效吗? – lys916

+0

是的,只是相应地更改构造函数,看到我更新的答案 – eol

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);  
?> 

,输出像 对象(球队)#1(0){}对象(球队)#2(0 ){}对象(球队)#3(0){}

如你期待:)