-1

您好,我正在学习 PHP 中的 OOP 编程,我正在尝试创建一个导航类(具有正确的 OOP 结构),但不知何故我无法使其工作。我不确定这些类是错误的还是我以错误的方式称呼它们..有人可以看看并帮助我解决这个问题:) 请参阅下面的代码

导航类:

<?php
class Navigation implements navigationInterface{

    public $menu = null;
    public $name = null;
    public $klasse = null;
    public $items = null;

    public function __construct($name, $klasse) {

        $this->name = $name;
        $this->klasse = $klasse;

    }

    public function addChild(NavigationItem $item)
    {
        $this->items[] = $item;
    }

    public function getName() {
        return $this->name;
    }

    public function getClass() {
        return $this->klasse;
    }


    public function display() {

        $menu = '<nav class="' . $this->getName() . '"><ul>';

        foreach ($this->items as $item) {

           $menu.= $item->display();

        }

        $menu .= '</ul></nav>';

        return $menu;

    }
}
?>

和我的导航项目类(添加项目)

<?php
class NavigationItem implements NavigationItemInterface {

    public $menu = null;

    public function setMenuItem($items) {

        $this->menuItem = $items;
    }

    public function getMenuItem() {
        return $items;
    }

    public function display() {


        return '<li><a class="' . $this->getClass() . '" href="index.php?page=' . $this->getMenuItem() . '.php">' . $this->getMenuItem() . '</a></li>';

    }

}
?>

这就是我认为我应该如何称呼这门课

<?php
$menu = new Navigation("navigation", "mainmenu");
$items = new NavigationItem();
$menu_items = array("home", "about", "playground");
$items->setMenuItem($menu_items);
$menu->addChild($items);
echo $menu->display();

?>
4

1 回答 1

0

问题是“它不起作用”。尝试这个。顺便说一句,在导航类中,这些公共字段应该是私有的。

<?php
   $menu = new Navigation("navigation", "mainmenu");
   $menu_items = array("home", "about", "playground");
   foreach($menu_items as $item) 
   { 
   $items = new NavigationItem();
   $items->setMenuItem($item);
   $menu->addChild($items);
    }
  echo $menu->display();

?>

于 2012-11-05T11:50:11.393 回答