我有麻烦调用我的PHP函数/方法


I have trouble calling my PHP function/method

我在调用类方法中的变量时遇到了麻烦。变量userId不会显示在屏幕上。下面是我的类和index.php文件。我想在表单提交后显示用户的userId。

class validateLogin 
{
    public $id;
    public $username;
    public $password;
    public function __construct($aUserName,$aUserPassword) 
    {       
        $this->username = $aUserName;
        $this->password = $aUserPassword;
    }
    public function checkUser() 
    {
        $conn = new dbconnection();
        $dbh = $conn->connect();
        $query = $dbh->prepare("SELECT id FROM tbluser WHERE username=:username AND password=:password");
        $query->bindParam(":username", $this->username);
        $query->bindParam(":password", $this->password);
        $query->execute();  
        $counts = $query->rowCount();       
        if($counts==1) {        
            $results = $query->fetch();
            $this->id = $results['id'];
        }
    }
    public function getUserId() {
        return $this->id;
    }       
}

我的index.php如下(假设已经点击了提交按钮)

require_once 'classes/class.Database.php';
require_once 'classes/class.Validation.php';
if(isset($_POST['submit'])) {
    if(!empty($_POST['username']) && !empty($_POST['password'])) {              
        $user = new validateLogin($_POST['username'],$_POST['password']);           
        echo getUserId()
    }
}

构造函数没有调用:

checkUser();

你需要让构造函数这样做或者:

require_once 'classes/class.Database.php';
require_once 'classes/class.Validation.php';
if(isset($_POST['submit'])) {
    if(!empty($_POST['username']) && !empty($_POST['password'])) {              
        $user = new validateLogin($_POST['username'],$_POST['password']);
        $user->checkUser();
        echo $user->getUserId();
    }
}

需要引用对象

echo getUserId()
应该

echo $user->getUserId()