Php 类对象的多个数组元素
将多个数组对象转换为类对象的最佳实践是什么 我有以下用例Php 类对象的多个数组元素,php,oop,Php,Oop,将多个数组对象转换为类对象的最佳实践是什么 我有以下用例 class Queue { private $id; public function getId() { return $this->id; } public function setId($id) { $this->id = $id; return $this; } private $name;
class Queue {
private $id;
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
return $this;
}
private $name;
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public static function getAll( ) {
// Guzzle HTTP Request returns JSON
$responseArray = json_decode ( $response->getBody() );
}
}
这是composer软件包的一部分。因此,现在当使用此队列
时,我们可以从父应用程序请求多个队列
。现在,我如何将这个json响应转换为Queue
对象
声明
getAll()
方法静态也是一个好的决定吗?我假设JSON响应包含一个关联数组,其中键是您想要在对象中使用的属性名。如果是,您可以使用中的解决方案。基本上,您只需遍历数组,并使用数组中的键作为属性名,使用值作为属性值:
$queue = new Queue();
foreach ($array as $key => $value)
{
$queue->$key = $value;
}
@Hassan所说的是正确的,如果按键不相同或重叠,你可以使用。您基本上需要将
json\u decode
给定的对象强制转换为Queu
对象并返回它
在这种情况下,静态是有意义的,因为您将在这里创建并返回一个Queu对象,如果您首先需要创建Queu对象,然后返回另一个Queu对象,则没有什么意义