在数组上添加元素

时间:2012-11-25 14:42:08

标签: php class constructor

我正在开发一个图形数据结构,但我遇到了一个问题:

<?php  
class Graph
{
    var $graph_arr = array();

    function Graph()
    {
        $this->graph_arr = array();
        //initialization of nodes, mythical for now
        $n = new Node("A", array("B", "C"));
        $this->graph_arr[] = $n;
        $n = new Node("B", array("A", "D"));
        $this->graph_arr[] = $n;
        $n = new Node("C", array("A", "E", "F"));
        $this->graph_arr[] =$n; 
        $n = new Node("D", array("B"));
        $this->graph_arr[] = $n;
        $n = new Node("E", array("C"));
        $this->graph_arr[] = $n;    
        $n = new Node("F", array("C"));
        $this->graph_arr[] = $n;
    }
};

class Node
{
    var $node_name;
    var $adjacent_nodes;
    var $is_visited;

    function Node($node_name, $adjacent_nodes)
    {
        $this->node_name = $node_name;
        $this->adjacent_nodes = $adjacent_nodes;
    }
    /** returns array of adjacent nodes **/

    function getAdjacentNodes()
    {
        return $this->adjacent_nodes;
    }

    function getNodeName()
    {
        return $this->node_name;
    }

    function isVisited()
    {
        return $this->is_visited;
    }

    function setVisited()
    {
        $this->is_visited = true;
    }
};

?>

当我创建Graph对象时,数组的大小为0.我无法添加新节点。

1 个答案:

答案 0 :(得分:1)

尝试更改您的Graph类:

class Graph
{
  var $graph_arr = array();

  function __construct() {
     $this->graph_arr = array();

   //initialization of nodes, mythical for now
   $n = new Node("A", array("B", "C"));
   $this->graph_arr[] = $n;
   $n = new Node("B", array("A", "D"));
   $this->graph_arr[] = $n;
   $n = new Node("C", array("A", "E", "F"));
   $this->graph_arr[] =$n; 
   $n = new Node("D", array("B"));
   $this->graph_arr[] = $n;
   $n = new Node("E", array("C"));
   $this->graph_arr[] = $n;    
   $n = new Node("F", array("C"));
   $this->graph_arr[] = $n;   
 }
}