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

0

6 Answers 6

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.

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

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.
The basic answer for me was: Don't define a function inside a another function.
3

Did you already declare A() somewhere else?

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

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

Comments

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.

Comments

0

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

Comments

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();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.