Mehulkumar
Mehulkumar

Reputation: 866

Fatal error: Class not found even though file is included which contains the class

I'm just trying to run a website on my local which I copied from server. In my config.php:

define ( 'DB_SERVER', '127.0.0.1' );
define ( 'DB_USERNAME', 'user' );
define ( 'DB_PASSWORD', 'password' );
define ( 'DB_DATABASE', 'database' );

class DB_Class {
    function __construct() {
        $connection = mysql_connect ( DB_SERVER, DB_USERNAME, DB_PASSWORD ) or die ( 'Connection error -> ' . mysql_error () );
        mysql_select_db ( DB_DATABASE, $connection ) or die ( 'Database error -> ' . mysql_error () );
    }
}

In my user.php:

include_once 'config.php';

class User {
    // Database connect
    public function __construct() {
        $db = new DB_Class ();
    }
}

In my index.php:

session_start ();
include_once ('classes/user.php');
$uobj = new User ();

Now whenever I attempt to create an object of a class User it returns a Fatal error: Class 'DB_Class' not found on the line where I attempt, in this case it's line 6. Though it works perfectly fine on server.

I tried to extend the class User to the class DB_Class but then again the same error on the line where I attempt to extend.

Someone please point out what's wrong. Thanks.

Upvotes: 2

Views: 3019

Answers (1)

Robbert
Robbert

Reputation: 6592

It appears that your site structure is set up with the two class files in a folder called classes. As this link suggests, relative paths in includes rarely go well because it's the calling script's path that is used for all includes, including those within other include files. Unless you have specified the classes folder as in your path, index.php won't know where the config.php file is. You should do this in your user.php file.

include_once $_SERVER['DOCUMENT_ROOT'] . '/classes/config.php';

Or use

require_once dirname(__FILE__) . '/config.php';

Either one will remove the relative link and allow the file to be included anywhere within your directory structure.

Upvotes: 2

Related Questions