简体   繁体   English

为什么会出现致命错误:不在对象上下文中时使用$ this?

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

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 $this is for objects. $this用于对象。 Use self to refer to the class a method is contained in when you don't have an instance. 当您没有实例时,使用self来指代方法所包含的类。

Remove static from you method signature if you want to use in object context. 如果要在对象上下文中使用,请从方法签名中删除static变量。

And more importantly, you spelled 'construct' incorrectly and typed 'pagename' instead of 'page_name'. 更重要的是,您拼写错误的“ construct”并键入“ pagename”而不是“ 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM