11

I have a function A in file B.inc

line 2:  function A() {

           ...

line 10: }

In the apache log:

PHP Fatal error: Cannot redeclare A() (previously declared in B.inc:2) in B on line 10

Bruce Dou
  • 4,673
  • 10
  • 37
  • 56

6 Answers6

18

I suppose you're using require "B.inc" in multiple parts? Can you try using require_once in all those instances instead?

Seems like your B.inc is parsed twice.

EboMike
  • 76,846
  • 14
  • 164
  • 167
4

I had a similar problem where a function entirely contained within a public function within a class was being reported as redeclared. I reduced the problem to

class B {
  function __construct() {
   function A() {
   }
  }
 }
 $b1 = new B();
 $b2 = new B();

The Fatal error: Cannot redeclare A() is produced when attempting to create $b2.

The original author of the code had protected the class declaration from being redeclared with if ( !class_exists( 'B' ) ) but this does not protect the internal function A() from being redeclared if we attempt to create more than one instance of the class.

Note: This is probably not the same problem as above BUT it's very similar to some of the answers in PHP Fatal error: Cannot redeclare class

Community
  • 1
  • 1
bobbingwide
  • 160
  • 6
  • This is similar to a problem I had, but my issue was having a named function defined inside a `foreach` loop. The solution ended up being using an anonymous function instead. – Mike Lyons Dec 01 '14 at 20:12
  • The basic answer for me was: Don't define a function inside a another function. – Daniel Tonon Jul 01 '15 at 03:19
3

Did you already declare A() somewhere else?

Or, are you calling B.inc twice on accident?

try using: require_once("B.inc");

Shackrock
  • 4,601
  • 10
  • 48
  • 74
0

Sounds like you might be including B.inc more than once.

// Rather than
include("B.inc");

// Do:
require_once("B.inc");

require_once() allows you to call on a file wherever necessary, but only actually parses it if not already parsed.

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
0

make sure that you require_once ( 'B.inc' ) or `include_once ( 'B.inc' )'

bensiu
  • 24,660
  • 56
  • 77
  • 117
0

These people are all right, but rather use php5, autoload, and instead of functions static methods. Object related methods are mostly better but using static methods enables you to reuse a method name in many classes. you can call a static method like this

ClassName::myFunction();
Jakob Alexander Eichler
  • 2,988
  • 3
  • 33
  • 49