0

这是database.php

class DatabaseConnection {
    private $host;
    private $port;
    private $dbname;
    private $username;
    private $password;
    public $query;


    function __construct($host, $port, $dbname, $username, $password) {
        $this->host = $host;
        $this->port = $port;
        $this->dbname = $dbname;
        $this->username = $username;
        $this->password = $password;

        try {
        $this->DBH = new PDO("pgsql:host=$this->host port=$this->port dbname=$this->dbname", "$this->username", "$this->password");
            //echo "PDO connection object created";
        }
        catch(PDOException $e) {
            echo $e->getMessage();
        }
    }


    function query($query) {
        $this->query = $query;
        $this->STH = $this->DBH->prepare($this->query);
        $this->STH->execute();
        $this->STH->setFetchMode(PDO::FETCH_ASSOC); 
    }

}
$db = new DatabaseConnection('11.22.33.444','5432','eu','eu','eu123');

这是我的授权.php

require 'database.php';

class Authorization extends DatabaseConnection {
    public $vk_id;
    public $eu_name;
    public $eu_society;
    public $eu_notes;
    public $eu_want_team;

    public function __construct() {
        $this->vk_id = $_POST['vk_id'];
        $this->eu_name = $_POST['eu_name'];
        $this->eu_society = $_POST['eu_society'];
        $this->eu_notes = $_POST['eu_notes'];
        $this->eu_want_team = $_POST['eu_want_team'];
    }
}
$auth = new Authorization();
$auth->query("INSERT INTO users (vk_id, eu_name, eu_society, eu_want_team, eu_notes) VALUES ($auth->vk_id, $auth->eu_name, $auth->eu_society, $auth->eu_want_team, $auth->eu_notes);");

我包含了 database.php 并将其扩展为能够在授权类中使用查询方法。但是现在它显示错误->

无法在第 2 行的 /home/marker/entropia/components/database.php 中重新声明类 DatabaseConnection

4

1 回答 1

2

当您的 PHP 应用程序加载时,解释器会多次遇到同一个类声明。

您可以通过以下任一方式防止这种情况发生...

  • 使用 include_once 或 require_once (如果同一文件的多个包含发生)
  • 使用命名空间(如果您需要使用同名的不同类)
  • 使用自动加载器类

...或检查类是否已经像这样声明:

if(!class_exists('MyClass'))
{
   // declare or include class here
}
于 2013-08-19T14:56:48.933 回答