PHP5如何用起始数组构建一个类?

时间:2013-02-15 21:41:48

标签: php arrays class menu menuitem

我在构建菜单时遇到问题,我想创建一个这样的类:

class leftMenu{

public $items;

    function addItem ($num){

        for($i = 0; $i < count($num); $i++){
              $this->items[$i] += $num;
              echo $this->items[$i];
            }

    }

public function __destruct() {
      //echo "\n</body>\n</html>";
    }

}

我想将addItem称为数组,例如:

$menu = new leftMenu();
$menu->addItem("one", "two", "three"); // Here 1, 2, 3 should be an array

我不能让它工作......请帮助!!! ND

3 个答案:

答案 0 :(得分:1)

您需要以下列方式更新您的代码(我刚刚初始化了变量$ items,以及您可以在评论中看到的另一个编辑):

class leftMenu{

public $items = array();  //intialize your variable $items

    function addItem ($num){

        for($i = 0; $i < count($num); $i++){
              $this->items[$i] = $num[$i]; //Edit this line too
              echo $this->items[$i];
            }

    }

public function __destruct() {
      //echo "\n</body>\n</html>";
    }

}

当你调用它时,像这样传递一个数组:

$menu = new leftMenu();
$menu->addItem(array("one", "two", "three")); // Here 1, 2, 3 should be an array

答案 1 :(得分:0)

$items = array("one", "two", "three");

$menu->addItems($items);


function addItems($items = array()) {
  $this->items = $items;
}

答案 2 :(得分:-1)

您需要将变量作为数组传递。试试这个:

$ menu-&gt; addItem(array(“one”,“two”,“three”));