简体   繁体   English

从同一个类中的函数调用PHP类中的函数

[英]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 . 我已经尝试过使用$this但是它给了我一个PHP错误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");
        }
    }
}

And no, I'm not creating the object 不,我不是在创造这个对象

This is why the call to $this->set_session($username); 这就是调用$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");
}

You must define set_session function as private . 您必须将set_session函数定义为private That way you can reference it using this->set_session 这样你就可以使用this-> set_session来引用它

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

如果你使用login作为类方法,那么你必须这样写:

SESSION::set_session($username);

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

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