【问题标题】:Add element on array在数组上添加元素
【发布时间】:2012-11-25 14:42:07
【问题描述】:

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

<?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。我无法添加新节点。

【问题讨论】:

  • 也许你需要像本手册中那样构造类:php.net/manual/en/language.oop5.decon.php
  • 将 var 更改为 public 或 private,在旧 PHP 4 中考虑使用 var
  • 哪个数组的大小变为零,您如何访问它。
  • 在 PHP 构造函数中添加了 __construct
  • 我解决了这个问题。我访问数组错误。现在我做对了。谢谢大家:)

标签: php class constructor


【解决方案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;   
 }
}  

【讨论】:

  • 你能选择我的答案作为答案吗? :D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-19
  • 2014-04-17
  • 2019-03-09
相关资源
最近更新 更多