我正在尝试制作动态菜单,但我不断收到致命错误。这是代码:
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);
}
}
}
?>
并用
调用它$nav = new Menu();
echo $nav->menu_list();
请帮我弄清楚它为什么不起作用。
答案 0 :(得分:1)
您无法在静态方法中使用$this
。 $this
用于对象。当您没有实例时,使用self
来引用包含方法的类。
如果要在对象上下文中使用,请从方法签名中删除static
。
更重要的是,你拼写了“构建”字样。错误地输入&#39; pagename&#39;而不是&#39; page_name&#39;。这有效:
<?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();