0

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 ?

1 Answer 1

2

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

    }
Sign up to request clarification or add additional context in comments.

3 Comments

then it will be an array of Graph object, But I need one Graph object which consists of many Edges as an array.
@MDeSilva please see my revised answer. By removing the constructor, you can create the item without first needing an Edge object, which allows you to just call your setEdges method in the loop on the existing Graph object, such that it won't be overwritten.
Leprichaun, Yes you are right, to be frank I was doing the same. and I think there is no any other way. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.