我有两个名为Edge and Graph的类,我需要通过循环和从Graph Object中检索,将一组边缘对象(在那些类外面)发送给Graph对象。
图表类
class Graph
{
/**
* Array of edge objects
*
* @var array
*/
protected $edges;
/**
* Set edges of the graph
*
* @param Edge edge object
*/
public function __construct(Edge $edge)
{
$this->setEdges($edge);
}
/**
* Get edges
*
* @return array array of edge objects
*/
public function getEdges()
{
return $this->edges;
}
/**
* Set Edges
*
* @param Edge Edge object
*/
public function setEdges(Edge $edge)
{
$this->edges[] = $edge;
}
}
通过边缘循环,
$edges = array(
array("point1" => "a", "point2" => "b", "value" => 7),
array("point1" => "a", "point2" => "c", "value" => 9),
array("point1" => "a", "point2" => "f", "value" => 14.00)
)
$graph = null;
foreach ($edges as $edge) {
$edgeObj = new Edge($edge['point1'], $edge['point2'], $edge['value']);
$graph = new Graph($edgeObj);
}
但是$ graph只返回最后一个Edge对象,我知道这是因为我覆盖了$ graph。我做错了什么?
答案 0 :(得分:2)
你完全自己回答了。您在循环的每次迭代时都会覆盖$graph
,并使用Graph
对象的全新实例。
首先,删除构造函数以允许您创建Graph
的实例而无需首先需要Edge
实例(即在循环外部),然后使用已编写的setEdges()
方法将每个新创建的Edge
实例添加到类中的数组中。
然后,将您的代码更改为:
$edges = array(
array("point1" => "a", "point2" => "b", "value" => 7),
array("point1" => "a", "point2" => "c", "value" => 9),
array("point1" => "a", "point2" => "f", "value" => 14.00)
)
$graph = new Graph();
foreach ($edges as $edge) {
$edgeObj = new Edge($edge['point1'], $edge['point2'], $edge['value']);
$graph->setEdges($edgeObj);
}