Cannot redeclare class - php [closed]

2020-05-03 10:17发布

问题:

This is 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');

And this is my authorization.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);");

I included database.php and extended it to be able to use query method in authorization class. But now it shows error - >

Cannot redeclare class DatabaseConnection in /home/marker/entropia/components/database.php on line 2

回答1:

When your PHP app loads, the interpreter comes across the same class declaration more than once.

You can prevent this from happening by either...

  • Using include_once or require_once (if multiple inclusions of the same file happen)
  • Using namespaces (if you need to use different classes of the same name)
  • Using an autoloader class

...or checking if class has already been declared like this:

if(!class_exists('MyClass'))
{
   // declare or include class here
}