简体   繁体   English

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

[英]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'). 我有一个字符串数组$ 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. 因此$ team1,$ team2和$ team3成为对象。

Thanks for your help. 谢谢你的帮助。

Assuming that Team has a property "name" just do it like this: 假设Team具有一个"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
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) { } 输出类似object(Team)#1(0){} object(Team)#2(0){} object(Team)#3(0){}

as you are expecting :) 正如您所期望的:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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