我无法在类方法中调用变量。变量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()
}
}
答案 0 :(得分:5)
构造函数未调用:
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();
}
}
答案 1 :(得分:1)
您需要引用对象
echo getUserId()
应该是
echo $user->getUserId()