0

I have been in toruble with kind of conflict issue. There is a Database Class which contains connection, update, delete, insert, fetch methods and also there is User Class which extends Database Class.

class User extends Database {...}

Problem is, when I initialize the Database class and User Class at the same time in "index.php", I get an fatal error which says "Fatal error: Cannot redeclare class Database".

include "database.class.php";
include "user.class.php;
$db = new Database;
$db->connect();

So, I am aware of initializing database class twice, but how can prevent not to happen? P.S.: I can use Database class in other new classes.

Ali Emre Çakmakoğlu
  • 864
  • 2
  • 12
  • 24

2 Answers2

1

Change the two "includes" you have for "require_once", as Michael said:

require_once "database.class.php";
require_once "user.class.php";
$db = new Database;
$db->connect();

Besides, if within the file "user.class.php" you are including the file "database.class.php", change it to "require_once" too.

I hope it helped!

alghimo
  • 2,899
  • 18
  • 11
1

In OOP the extends means "is a". What you have written there says: "User is a Database". Which is certifiably bonkers.

Instead of extending the database class, you should be injecting it into constructor of User instance:

$database = new Database(...);
$database->connect();
$user = new User( $database );

Always favor composition over inheritance.

As for all that require_once mess .. just learn how to use spl_autoload_register().

tereško
  • 58,060
  • 25
  • 98
  • 150
  • Can you give an example how am I gonna use? how should constructor of user class supposed to be? This usage is kind of strange to me. – Ali Emre Çakmakoğlu Apr 02 '12 at 20:34
  • @GncArt , constructor of any class should be only assigning values to local variables. In a well written object oriented code, constructors don't do any "work". – tereško Apr 02 '12 at 20:40
  • @GncArt , if you really want to learn more about OOP, you should watch few lectures on subject. If you scroll to "OOP beyond classes" part of [this comment](http://stackoverflow.com/questions/9846220/php-oop-core-framework/9855170#9855170), there will be a list of video on the subject. Watch them. You will learn a lot from them .. I sure did. – tereško Apr 03 '12 at 06:26