I am trying to make a dynamic menu, but I keep getting the fatal error. Here is the code:
class Menu {
public $menu;
function __contstruct() {
$this -> menu = array("Home" => "index.php",
//"Eat" => array("Casual" => "casual.php", "Fine dining" => "fine_dining.php"),
"Contact" => "contact.php");
}
public static function page_name() {
return substr($_SERVER["SCRIPT_NAME"], strrpos($_SERVER["SCRIPT_NAME"], "/") + 1);
}
public static function menu_list() {
$menu_list = "";
foreach ($this->menu as $name => $url) {
echo "<li ";
if ($url == $this -> pagename()) {
$menu_list .= "class='active'";
}
$menu_list .= "><a href='";
$menu_list .= $url;
$menu_list .= "'>" . $name . "</a></li>";
return ($menu_list);
}
}
}
?>
and calling it with
$nav = new Menu();
echo $nav->menu_list();
Please help me figure why it isn't working.
You can't use $this
in a static method. $this
is for objects. Use self
to refer to the class a method is contained in when you don't have an instance.
Remove static
from you method signature if you want to use in object context.
And more importantly, you spelled 'construct' incorrectly and typed 'pagename' instead of 'page_name'. This works:
<?php
class Menu {
public $menu;
function __construct() {
$this -> menu = array("Home" => "index.php",
//"Eat" => array("Casual" => "casual.php", "Fine dining" => "fine_dining.php"),
"Contact" => "contact.php");
}
public function page_name() {
return substr($_SERVER["SCRIPT_NAME"], strrpos($_SERVER["SCRIPT_NAME"], "/") + 1);
}
public function menu_list() {
$menu_list = "";
foreach ($this->menu as $name => $url) {
echo "<li ";
if ($url == $this -> page_name()) {
$menu_list .= "class='active'";
}
$menu_list .= "><a href='";
$menu_list .= $url;
$menu_list .= "'>" . $name . "</a></li>";
return ($menu_list);
}
}
}
$nav = new Menu();
echo $nav->menu_list();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.