Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: cannot declare class because the name is already in use

Tags:

oop

php

I have 5 scripts:

  1. database.php
  2. parent.php
  3. child1.php
  4. child2.php
  5. somescript.php

parent.php class looks like this:

include 'database.php';

class Parent {
    public $db;
    function __construct() {
        $this->db = new Database();
    }
}

The child1.php and child2.php classes looks like this:

include 'parent.php';

class Child1 extends Parent {
    function __construct() {
        parent::__construct();
    }

    function useDb() {
        $this->db->some_db_operation();
    }
}

The problem

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

cannot declare class Database because the name is already in use in database.php on line 4 (this is the line which contains words 'class Database')

But if I include only a single file (child1 or child2), it works great.

How do I correct that?

like image 899
egorik Avatar asked Mar 08 '17 21:03

egorik


3 Answers

You want to use include_once() or require_once(). The other option would be to create an additional file with all your class includes in the correct order so they don't need to call includes themselves:

"classes.php"

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

Then you just need:

require_once('classes.php');
like image 117
M31 Avatar answered Oct 24 '22 07:10

M31


try to use use include_onceor require_once instead of include or require

like image 11
Solaymane Chamane Avatar answered Oct 24 '22 07:10

Solaymane Chamane


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

like image 4
Fergal Andrews Avatar answered Oct 24 '22 06:10

Fergal Andrews