簡體   English   中英

為什么會出現致命錯誤:不在對象上下文中時使用$ this?

[英]Why am I getting the Fatal error: Using $this when not in object context?

我正在嘗試制作動態菜單,但我一直收到致命錯誤。 這是代碼:

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();

請幫我弄清楚為什么它不起作用。

您不能在靜態方法中使用$this $this用於對象。 當您沒有實例時,使用self來指代方法所包含的類。

如果要在對象上下文中使用,請從方法簽名中刪除static變量。

更重要的是,您拼寫錯誤的“ construct”並鍵入“ pagename”而不是“ page_name”。 這有效:

<?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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM