0

Alright I have a few classes and I'm wanting to pass on an initiated class object but I keep getting errors. It'll work one time, then other times I'll get a

PHP Fatal error: Cannot redeclare class

I don't know what I'm doing wrong. I'm basically trying to clean up my code because I'm ALWAYS having 2-3 includes for every one of my pages. I'd rather just include one class and pass on or use the other classes instances from there. Here's an example of what I have now:

Manage.php - Main Class

<?php

include_once('/path/to/DB.php');

class Manage {

    public $db;

    public function __construct() {
        $this->db = new DB($host,$dbName,$user,$pass);
        //other constructor stuff
    }

    //other functions
}

DB.php - Helper Class

<?php

class DB {

    public $conn;

    public function __construct($host = false, $db = false, $user = false, $pass = false) {
        //connect to database
    }

    //functions for interacting with the database (get,query,update,insert, etc)
}

UseOfClass.php - Shows how I'd like to use it

<?php
include('/path/to/Manage.php');
$manage = new Manage();

$results = $manage->db->get('table_name');

print_r($results);
Andrew
  • 175
  • 1
  • 2
  • 12
  • Which line is that error occuring on? – gen_Eric Sep 09 '15 at 15:11
  • @RocketHazmat - on the "class DB {" line – Andrew Sep 09 '15 at 15:13
  • 1
    since it's saying "can't redeclare", somewhere you're doing an `include()` instead of `include_once()` and re-loading the DB.php file. – Marc B Sep 09 '15 at 15:14
  • 1
    Try using include_once in UseOfClass.php, instead of include – Craig Sep 09 '15 at 15:15
  • 1
    Loading the classes you need automatically, without `include` or `require`'ing the files manually... if only [autloading classes](http://php.net/manual/en/language.oop5.autoload.php) were possible. Wait is it? Great... read the docs! – Elias Van Ootegem Sep 09 '15 at 15:23
  • "I'm ALWAYS having 2-3 includes for every one" - Have you maybe thought about using something like an initialisation script? So in that you can define system params, initialise any required classes then pass off to the router to load the required models, controllers, or views? Read here, you might find some ideas: http://requiremind.com/a-most-simple-php-mvc-beginners-tutorial/ – Craig van Tonder Sep 09 '15 at 15:27
  • possible duplicate of [When should I use require\_once vs include?](http://stackoverflow.com/questions/2418473/when-should-i-use-require-once-vs-include) – Peter Uhnak Sep 09 '15 at 21:53

0 Answers0