开发者

PHP Fatal error: Cannot redeclare function [duplicate]

开发者 https://www.devze.com 2023-02-17 03:13 出处:网络
This question already has answers here: 开发者_如何学JAVA"Fatal error: Cannot redeclare <function>"
This question already has answers here: 开发者_如何学JAVA "Fatal error: Cannot redeclare <function>" (18 answers) Closed 4 years ago.

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


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.


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


Did you already declare A() somewhere else?

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

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


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.


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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号