Calling a function inside a PHP class from a function inside a single class
I have the code below that won't run due to not being able to find out how to call a function that is in the same class as another function. I've already tried using $this
, but it gives me PHP error Using $this when not in object context...Line 25
. I have no idea how to fix this, and I hope someone else can give me some advice 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");
}
}
}
And no, I am not creating an object
This is why the call $this->set_session($username);
fails, if you want to follow the same pattern of code you have you can do this:
if ($num == 0) {
header("Location: login.php?e=1");
} elseif ($num == 1) {
self::set_session($username);
header("Location: admin.php");
}
If you are using the login method as a class, then you should write like this:
SESSION::set_session($username);
You must define the set_session function as private . This way you can reference it with this-> set_session
private function set_session($username) {
$_SESSION["username"] = $username;
}