将对象存储在数组中并使用 PHP 检索

Storing objects in an array and retrieving using PHP

我有两个 类 称为 Edge 和 Graph,我需要通过循环将一组边对象(在那些 类 之外)发送到 Graph 对象并从 Graph 对象中检索。

图表Class

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 returns 只有最后一个 Edge 对象,我知道这是因为我覆盖了 $graph。我做错了什么?

你自己回答的很完美。您在循环的每次迭代中都覆盖 $graph,并使用 Graph 对象的全新实例。

首先,删除你的构造函数以允许你创建一个 Graph 的实例,而不需要首先需要一个 Edge 实例(即,在你的循环之外),然后使用你已经编写的 setEdges() 方法将每个新创建的 Edge 实例添加到 class.

中的数组

然后,将您的代码更改为:

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

    }