【发布时间】:2014-08-11 19:52:50
【问题描述】:
在我的 PHP 文件中,我有一个包含所有函数的类,我正在使用这个类与另一个文件进行交互。这是我正在使用的代码:
public function check_user_exists ($username_original) {
try {
$db_connect = SQLConnect(); // Make the PDO handle usable
// Prepare and fetch the id of the user trying to login, used to validate whether the user exists or not
$db_interact = $db_connect->prepare("SELECT `id` FROM `users` WHERE `username_raw` = :username_raw");
$db_interact->bindParam(":username_raw", $username_original);
$db_interact->setFetchMode(PDO::FETCH_ASSOC);
$db_interact->execute();
$db_fetch = $db_interact->fetch();
if ($db_fetch == false) {
return false;
} else {
global $validation_code;
$validation_code = $db_fetch["id"];// Used to log the id of the use0r logging in
return true;
}
} catch (PDOException $e) {
echo $e->getMessage; // Used if something goes wrong with the PDO statement
}
}
这是一个使用 PDO 来检查数据库中是否存在用户的简单函数。
正如您在第三行代码中看到的,该函数引用了SQLConnect()。当我使用函数check_user_exists() 时,它给了我一个致命错误,说我调用了一个未定义的函数,除了SQLConnect() 在同一个文件中,并且在同一个PHP 类中。
这是SQLConnect():
// Function to allow database interactions
public function SQLConnect () {
// Database connection variables
$host = "localhost";
$dbname = "dropbox-database";
$user = "root";
$password = "password";
// Set connect to null
static $connect = null;
if (is_null($connect)) {
try {
// Database connection variables
$host = "localhost";
$dbname = "dropbox-database";
$user = "root";
$password = "ethan17458";
// Initiate connection
$connect = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
// Set error mode
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
} catch (PDOException $e) {
// If there is an error, echo error message
echo $e->getMessage();
}
// Make $connect usable
return $connect;
}
}
我正在使用这个函数通过 PDO 打开一个数据库连接。
当这两个函数在同一个文件中并且在同一个类中时,为什么会触发一个致命错误?我该如何解决这个问题?
谢谢,
伊森
【问题讨论】:
-
因为类中的函数是类的方法,而不是全局可访问的函数。您可以通过 $this->SQLConnect() 访问它
-
谢谢!我试过了,效果很好。
-
我发布了一个答案,所以你可以接受它