0

i recently started learning PDO and OOP to make my websites safer and faster. i am having some issues with OOP in PHP. i have a folder named res (short for resources) and a folder named classes and an index.php file, in the res folder i have a menu.php file that needs two classes named class.ManageUsers.php and class.ManageNews.php. in both of these files i am including class.database.php, here is the code for that file:

<?php

    class dbConnection {

        protected $db_conn;
        public $db_name = 'red_sec_net';
        public $db_user = 'root';
        public $db_pass = '';
        public $db_host = 'localhost';

        function connect(){
            try{
                $this->db_conn = new PDO("mysql:host=$this->db_host;dbname=$this->db_name;",$this->db_user,$this->db_pass);
                $this->db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                return $this->db_conn;
                $this->conn = null;
            }catch(PDOException $e){
                die('failed to connect to database');
            }
        }
    }

?>

now in the index.php file i need class.ManageUsers.php so i include it just before i include menu.php but when i go to that page i get this error:

Cannot redeclare class dbConnection in C:\wamp64\www\redsec\classes\class.database.php on line 3

the people i consulted said i should close the connections so i did that using

$this->link = null; and all the other variables that contained anything related to the connection after i do return what i need.
this is my constructor method:

class ManageUsers {

public $link;

function __construct(){

    $db_connection = new dbConnection();
    $this->link = $db_connection->connect();
    return $this->link;
    $this->link = null;

}
}

all my attempts have failed and i am starting to pull my hair out any help appreciated

i believe the error is happening in the constructor method when i do $db_connection = new dbConnection();

red security
  • 193
  • 3
  • 14

1 Answers1

-1

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

Try this:

include_once or require_once (if multiple inclusions of the same file happen)

Probably this could be a duplicated: Cannot redeclare class - php

Community
  • 1
  • 1
al27091
  • 111
  • 5
  • OMG it worked thank you. i did not know the difference between them and i usually use them all can you explain please? – red security Jan 23 '17 at 07:41
  • 1
    require_once simply checks if the file has already been included; if it has, it skips the iteration. If it hasn't, then it includes it. It's always best to use require_once() vs require. – Kaylined Jan 23 '17 at 07:42
  • Thank you for the explanation :) fast and to the poitn – red security Jan 23 '17 at 08:37