在函数中插入变量


insert variable in function

我是oop的新手,我还没有发现如何在函数Login()中插入$status的值。我做错了什么??因为我得到这个错误:

警告:User::Login()缺少参数3,在E:'xampp'htdocs'caps'index.php第13行调用,在E:'xampp'htdocs'caps'class' User .php第20行定义

class User {
private $db;
public $status;
public function __construct() {
    $this->db = new Connection();
    $this->db = $this->db->dbConnect();
    $this->status = pow( 1, -1*pi());   
}

public function Login ($name, $pass, $status) {
    if (!empty($name) && !empty($pass))  {
        $st = $this->db->prepare(" select * from users where name=? and pass=? ");
        $st->bindParam(1, $name);
        $st->bindParam(2, $pass);
        $st->execute();
        if ($st->rowCount() != 1) {         
                echo "<script type='"text/javascript'">alert ('wrong password. try again'); window.location='"index.php'"; </script>";
        } else {
            $st = $this->db->prepare(" select * from users where name=? and pass=? status=?");
            $st->bindParam(1, $name);
            $st->bindParam(2, $pass);
            $st->bindParam(3, $status);             
            $st->execute();
                if ($st->rowCount() != 1) { echo "send user to user page"; } else { echo "send user to admin"; }
        }
    } else {
    echo "<script type='"text/javascript'">alert ('insert username and password'); window.location='"index.php'"; </script>";
    }

}

}

如果您希望使用$status的值,则从登录函数中删除该参数,并将$status替换为$this->status

public function Login ($name, $pass) {
if (!empty($name) && !empty($pass))  {
    $st = $this->db->prepare(" select * from users where name=? and pass=? ");
    $st->bindParam(1, $name);
    $st->bindParam(2, $pass);
    $st->execute();
    if ($st->rowCount() != 1) {         
            echo "<script type='"text/javascript'">alert ('wrong password. try again'); window.location='"index.php'"; </script>";
    } else {
        $st = $this->db->prepare(" select * from users where name=? and pass=? status=?");
        $st->bindParam(1, $name);
        $st->bindParam(2, $pass);
        $st->bindParam(3, $this->status);             
        $st->execute();

或者您可以通过将函数声明更改为$status = $this->status来使构造函数值为"默认值",并且如果需要的话,这将允许您在调用函数时覆盖状态值。

这意味着您调用了$user->Login而没有提供第三个参数。

如果你希望这个参数是可选的,你可以将方法签名更改为

public function Login ($name, $pass, $status = null) {

如果你想让状态默认为你的状态属性,你可以用

开始你的Login函数
public function Login ($name, $pass, $status = null) {
        if(!$status) $status = $this->status;
        //...the rest of your code
 }

正确的调用方法是:

$user = new User();
$user->Login($username, $password, $status);