PHP: it is not possible to declare a class because the name is already in use

I have 5 scripts, say: database.php, parent.php, child1.php, child2.php and somescript.php

The parent.php class is as follows:

include 'database.php'; class Parent { public $db; function __construct() { $this->db = new Database(); } } 

The child1 and child2 classes look like this:

 include 'parent.php'; class Child1 extends Parent { function __construct() { parent::__construct(); } function useDb() { $this->db->some_db_operation(); } } 

Problem

When I try to include child1 and child2 in somescript.php, it returns the following error:

cannot declare a class database, because the name is already used in database.php on line 4 (this is a line containing a database of word classes)

But if I include only one file (child1 or child2), it works fine.

How to fix it?

+28
oop php
source share
4 answers

you want to use include_once () or require_once () . Another option is to create an additional file with all your classes in the correct order so that they do not need to be included:

"classes.php"

 include 'database.php'; include 'parent.php'; include 'child1.php'; include 'child2.php'; 

Then you just need to:

 require_once('classes.php'); 
+30
source share

try using include_once or require_once instead of include or require

+10
source share

Another option to include_once or require_once is to use class autoload. http://php.net/manual/en/language.oop5.autoload.php

+2
source share

I had this problem before, and to fix it, just make sure:

  1. You did not instantiate this class until
  2. If you are calling this from a class method, make sure that __destruct is set in the class from which you called.

My problem (before):
I had a class: Core, Router, Permissions, and Render. The kernel includes the Router class, then Router calls the Permissions class, then Router __destruct calls the Render class, and the error message β€œUnable to declare the class because the name is already in use,” appears.

Decision:
I added __destruct for the Permission class, and __destruct was empty, and it fixed ...

0
source share

All Articles