Search code examples
phpoopsymfonyzend-framework

Storing objects in an array and retrieving using PHP


I have two classes called Edge and Graph, I need to send set of edge objects (out side those classes) to Graph object by looping and retrieve from Graph Object.

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;

}

}

Looping through edges,

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

}

But $graph returns only last Edge object, I know it's because I overwrite $graph. What am I doing wrong ?


Solution

  • You answered it yourself perfectly. You're overwriting $graph with each iteration of your loop, with a completely new instance of a Graph object.

    First, remove your constructor to allow you to create an instance of Graph without first needing an Edge instance (ie, outside your loop), then use your already written setEdges() method to add each newly created Edge instance to your array in the class.

    Then, change your code to this:

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