JDDoesDev
JDDoesDev

Reputation: 386

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.

Upvotes: 0

Views: 49

Answers (1)

Calvin Froedge
Calvin Froedge

Reputation: 16373

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

Upvotes: 2

Related Questions