【发布时间】:2016-12-04 18:11:18
【问题描述】:
我来自 Java 编程,我正在尝试在 PHP 中应用我在 OOP 样式编程方面的知识。
所以,我尝试创建一个实用程序类来连接到数据库,就像我通常在 Java 中所做的那样,我创建一个静态方法来获取数据库连接。
但是,在花费数小时后,我仍然无法修复错误。
DBHelper.php
<?php
class DBHelper
{
protected $db_name = 'myDb';
protected $db_user = 'root';
protected $db_pass = '';
protected $db_host = 'localhost';
public function obtainConnection()
{
$mysqli_instance = new mysqli($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
return $mysqli_instance;
}
}
?>
此文件中没有错误
然后我尝试在另一个名为login.php的文件上使用它
login.php
<?php
if (isset($_POST['submit'])) {
include "/DBUtility/DBHelper.php";
$username = $_POST['username']; //s means string
$password = $_POST['password']; // s means string
echo "<br/> Username value: " . $username;
echo "<br />Password value: " . $password;
}
if (empty($username) || empty($password) ) {
echo "Fill out the fields!";
} else {
//PREPARE THE PreparedStatment or Stored Procedure
$dbHelper = new DBHelper();
$connection = $dbHelper->obtainConnection();
$preparedStatement = $connection->prepare('CALL getUserRoleByLogin(?, ?)'); //getUserRoleByLogin() is the name of stored proc in mysql db
$preparedStatement->bind_param('ss', $username, $password); //assign arguments to ? ?
$preparedStatement->execute();//execute the stored procedure. This will return a result
$userRole = $preparedStatement->store_result();
$countOfRows = $preparedStatement->num_rows;
?>
我阅读了有关 Fatal error: Cannot redeclare class CLASSNAME 错误的所有相关问题。我尝试按照许多人给出的说明使用require_once("DBHelper.php"); 而不是include("DBHelper.php");
但仍然无法摆脱错误。
我尝试将obtainConnection() 设为静态并通过DBHelper::obtainConnection(); 调用它,但没有运气。同样的错误信息。
class DBHelper{ 的左大括号出现错误
希望你能帮我解决这个问题。
谢谢。
【问题讨论】:
-
好吧,你是对的
require_once或include_once。是不是说你不能重新声明“DBHelper”或者类名是什么? -
@Rasclatt 首先,谢谢。是的,我收到错误致命错误:无法重新声明类 DBHelper
-
其他原因可能是 1)您使用的名称与已经在其他地方(可能由其他人)创建的类相同,在这种情况下您应该使用命名空间 2)也许您复制了这个文件以重命名和扩展它,忘记更改重复文件上的类名。
-
另外,如果你只是在做 PHP 新手,我建议使用
PDO而不是mysqli_,虽然这是个人喜好,但我认为你会发现绑定值更容易,而且只需一般来说更容易。您可以像$preparedStatement->execute(array(":0"=>$username,":1"=>$password));一样将数组直接放入您的execute(),我发现PDO 更容易自动化和使用,但就像我说的,这是个人喜好。