Using Array in PHP Class
class, php
Solution
<?php
class Navigation{
public $menu = null;
public $name = null;
public $klasse = null;
public function __construct($name, $klasse) {
$this->name = $name;
$this->klasse = $klasse;
}
public function getName() {
return $this->name;
}
public function getClass() {
return $this->klasse;
}
public function setMenuItem($items) {
$this->menuItem = $items;
}
public function getMenuItem($menu) {
return $menu;
}
public function display() {
$menu = '<nav class="' . $this->getName() . '">';
if(is_array($this->menuItem))
{
foreach($this->menuItem as $val)
{
$menu .= '<li><a class="' . $this->getClass() . '" href="index.php?page=' . $this->getMenuItem($val) . '.php">' . $this->getMenuItem($val) . '</a></li>';
}
}
else{
$menu .= '<li><a class="' . $this->getClass() . '" href="index.php?page=' . $this->getMenuItem($this->menuItem) . '.php">' . $this->getMenuItem($this->menuItem) . '</a></li>';
}
$menu .= '</nav>';
return $menu;
}
}
?>
<?php
$menu = new Navigation("Test", "mainmenu");
$menu_items=array("home","test");
$menu->setMenuItem($menu_items);
echo $menu->display();
?>
Problem
I am exercising some PHP OOP and therefore I am creating a class to create a simple navigation menu ( with extensions in the future ) now I have build this class that works kinda.. with 1 menu item tough.. I don;t know how to use arrays in my class to use the class like ``` <?php $menu = new Navigation("Test", "mainmenu"); $menu->setMenuItem("home", "test"); echo $menu->display(); ?> ``` as you see I should be able to give each menu item with the setMenuItem(); method. but since it does not use Arrays at the moment I only get the first value The class itself is as follows: ``` <?php class Navigation implements navigationInterface { public $menu = null; public $name = null; public $klasse = null; public function __construct($name, $klasse) { $this->name = $name; $this->klasse = $klasse; } public function getName() { return $this->name; } public function getClass() { return $this->klasse; } public function setMenuItem($items) { $this->menuItem = $items; } public function getMenuItem() { return $this->menuItem; } public function display() { $menu = '<nav class="' . $this->getName() . '">'; $menu .= '<li><a class="' . $this->getClass() . '" href="index.php?page=' . $this->getMenuItem() . '.php">' . $this->getMenuItem() . '</a></li>'; $menu .= '</nav>'; return $menu; } } ?> ``` who can show me how to use arrays within the class in combination with a loop to create a menu with all given values? Thanks in advance.