Josh Ferrara
Josh Ferrara

Reputation: 767

Calling a function inside a PHP class from a function within the same class

I have some code below which will not run due to me not being able to know how to call a function that's within the same class as another function. I've already tried using $this but it gives me a PHP error Using $this when not in object context...Line 25. I have no clue how to fix this and I'm hoping someone else can give me some tips on what to do. My code is below, thanks :)

class SESSION {
    function start() {
        session_start();
    }
    function check() {
        if ($_SESSION["username"]) {
            return $_SESSION["username"];
        } else {
            return "nli"; //Not logged in :(
        }
    }
    function set_session($username) {
        $_SESSION["username"] = $username;
    }
    function login($username, $password) {
        $database = DB::connect();
        $passwordsha = sha1($password);
        $query = "";
        $res = $database->query($query);
        $num = $res->num_rows;
        if ($num == 0) {
            header("Location: login.php?e=1");
        } elseif ($num == 1) {
            $this->set_session($username);
            header("Location: admin.php");
        } else {
            header("Location: login.php?e=2");
        }
    }
}

Upvotes: 3

Views: 14771

Answers (3)

Xabier Aberasturi
Xabier Aberasturi

Reputation: 31

You must define set_session function as private. That way you can reference it using this->set_session

private function set_session($username) {
    $_SESSION["username"] = $username;
}

Upvotes: 0

Mike Purcell
Mike Purcell

Reputation: 19979

And no, I'm not creating the object

This is why the call to $this->set_session($username); is failing, if you want to follow the same code pattern you have in place you can do this:

if ($num == 0) {
    header("Location: login.php?e=1");
} elseif ($num == 1) {
    self::set_session($username);
    header("Location: admin.php");
}

Upvotes: 9

PasteBT
PasteBT

Reputation: 2198

If you use login as class method, then you have to write like this:

SESSION::set_session($username);

Upvotes: 0

Related Questions