致命错误:无法重新声明类数据库。怎么修?

时间:2014-09-02 22:28:05

标签: php mysql

我已经看到了问题,但答案对我来说并不是很清楚。 我的代码是。

的index.php

 <?php include 'header.php'; ?>
    <?php
      include "class.users.php";
      if(isset($_POST['login'])) {
        $username = $_POST['username1'];
        $password = $_POST['password1'];
        $users->login($username, $password);
      }
    ?>

class.users.php

<?php
  include "connect.php";
  class Users extends Database {
    public function login($username, $password) {
      $stmt = $this->mysqli->prepare("SELECT username, password FROM users WHERE username = ? AND password = ? LIMIT 1");
      $stmt->bind_param('ss', $username, $password);
      $stmt->execute();
      $stmt->bind_result($username, $password);
      $stmt->store_result();
      if($stmt->num_rows == 1) {
        while($stmt->fetch()) {
          $_SESSION['username'] == $username;
          header("Location: dashboard.php");
        }
      } else {
          return false;
      }
      $stmt->close();
      $stmt->free_result();
    }
  }
  $users = new users();
?>

connect.php

<?php

    class Database {
      public function __construct() {
        $host = 'localhost';
        $user = 'root';
        $pass = '';
        $name = 'meeboo3';
        $this->mysqli = new mysqli($host, $user, $pass, $name);
      }
    }
    ?>

类数据库没有被调用两次?那怎么回事?任何人都可以在评论中解释原因。

1 个答案:

答案 0 :(得分:1)

你可以在这之前测试它是否已经声明:

if (!isset($database) && !is_a($database, 'Database')){
  $database = new Database();
}

或者

如果你在connect.php内声明它,你可以:

include_once 'connect.php';

而不是

include 'connect.php';