Php error fatal error cannot redeclare class

Fatal error: Cannot redeclare class Database

Check inside your user.php or message.php file. You have already include a database.php file where class Database is already declared.

3 Answers 3

You include 2 files in a single «run». Think of it like this: All the included files are put together by PHP to create one big script. Every include or require fetches a file, and pastes its content in that one big script.

The two files you are including, both require the same file, which declares the Database class. This means that the big script that PHP generates looks like this:

class Message <> class Database <>//required by message.php class User <> class Database <>//required by user.php 

As you can see class Database is declared twice, hence the error.
For now, a quick fix can be replacing the require(‘database.php’); statements with:

Which checks if that particular file hasn’t been included/required before. If it has been included/required before, PHP won’t require it again.
A more definitive and, IMHO, better solution would be to register an autoloader function/class method, and let that code take care of business.

More on how to register an autoloader can be found in the docs. If you go down this route, you’d probably want to take a look at the coding standards concerning class names and namespaces here. If you conform to those standards, you don’t have to write your own autoloader, and can simply use the universal class loader from Symfony2, or any other framework that subscribes to the PHP-FIG standards (like CodeIgnitor, Zend, Cake. you name it)

Читайте также:  Php strpos empty delimiter

Источник

PHP Fatal error: Cannot redeclare class

to prevent multiple inclusions. It’s very easy for this to happen, though not always obvious, since you could have a long chain of files being included by one another.

@Timo Based on benchmarks I’ve looked at, there will only be a noticeable difference of about 1 second if you have a file with 100,000 include_once’s. You would be better off optimizing your DB access or other logic than prematurely optimizing your file includes using substandard techniques like master include files. The autoload feature doesn’t perform significantly differently. Each functions differently, and are not interchangeably appropriate. You can use one for the other, but there are corner cases where they do not function the same.

@Timo To quote the page you linked «using __autoload() is discouraged and may be deprecated or removed in the future.»

@AaronLS Can’t edit comments on SO, the link also links to the better example. I suggested it after reading APC’s developers comments and how he hated include_once (I felt bad for him). Also the difference is beyond just performance.

It means you’ve already created a class.

class Foo <> // some code here class Foo <> 

That second Foo would throw the error.

This answer is not as helpful as AaronLS’s. I don’t think the questioner would have asked the question if (s)he had written an obvious repetition like this (even in quite a complex situation). The include_once tip helps to clarify an obscure feature of PHP.

Just use include_once(‘FooBar.php’) to include your class. The name of the function is self-explanatory.

Actually this answers the question perfectly and it is timeless, AaronLS makes an assumption then attempts to solve the problem which can now be solved many better ways.

That happens when you declare a class more than once in a page. You can fix it by either wrapping that class with an if statement (like below), or you can put it into a separate file and use require_once() , instead of include() .

In @Jens-AndréKoch comment a «s» is missing in the second example —> it’s class_exists(‘TestClass’) === false or !class_exists(‘TestClass’)

Use include_once(); — with this, your codes will be included only one time.

This will happen if we use any of the in built classes in the php library. I used the class name as Directory and I got the same error. If you get error first make sure that the class name you use is not one of the in built classes.

Golden answer in here for me — I didn’t even think PHP might have had the same class name as I was using!

This error might also occur if you define the __construct method more than once.

Sometimes that happens due to some bugs in PHP’s FastCGI.

Try to restart it. At Ubuntu it’s:

service php-fastcgi restart 

Ok, it’s a solution but it doesn’t correct the problem And in my case, the problem appears randomly one or two times by month. 🙁

@SkaJess — you can add restart command to crontab to restart hourly. dirty — but will assure that max downtime of your site will be 1 hour.

@how — it’s not a good solution for me because php is falling down during the working day. I think that in one way that I’ll add restart command daily during the night. In the second way, i ll consider to upgrade IIS and PHP.

I had the same problem while using autoload like follows:

 __autoload("MyClass1"); $obj = new MyClass1(); ?> 

and in other class there was:

namespace testClassNamespace; class MyClass1 < function __construct() < echo "MyClass1 constructor"; >> 

The sollution is to keep namespace compatibility, in my example namespace testClassNamespace; in both files.

This error can also occur if you by mistake put a function inside another function.

PHP 5.3 (an I think older versions too) seems to have problem with same name in different cases. So I had this problem when a had the class Login and the interface it implements LogIn. After I renamed LogIn to Log_In the problem got solved.

Just do one thing whenever you include or require filename namely class.login.php. You can include it this way:

include_once class.login.php or require_once class.login.php 

This way it never throws an error.

This function will print a stack telling you where it was called from:

function PrintTrace() < $trace = debug_backtrace(); echo '
'; $sb = array(); foreach($trace as $item) < if(isset($item['file'])) < $sb[] = htmlspecialchars("$item[file]:$item[line]"); >else < $sb[] = htmlspecialchars("$item[class]:$item[function]"); >> echo implode("\n",$sb); echo '

'; >

Call this function at the top of the file that includes your class.

Sometimes it will only print once, even though your class is being included two or more times. This is because PHP actually parses all the top-level classes in a file before executing any code and throws the fatal error immediately. To remedy this, wrap your class declaration in if(true) < . >, which will move your class down a level in scope. Then you should get your two traces before PHP fatal errors.

This should help you find where you class is being included from multiple times in a complex project.

Источник

php fatal error cannot redeclare class – How to fix?

A few days ago, we came across this error message due to which our customer was not able to continue with coding for a long time.

At Bobcares, we often get requests to fix PHP fatal errors, as a part of our Server Management Services.

Today, we’ll have a deep look into PHP fatal errors and see how our Support Engineers fix them.

Why does PHP fatal error occur?

We’ve seen many of our customers experiencing this error. Usually, this error causes an immediate termination of the script.

Basically, ‘PHP fatal error cannot redeclare class’ indicates that the class name already exists.

Mostly, this error shows up while the user is adding some new PHP codes. But WordPress sites also show the same error due to plugin or theme conflicts.

Let’s see both these instances in detail.

1. Error while coding

PHP fatal error is quite common while coding. Developers often get the error message when trying to declare an already existing class. The error message appears as:

PHP Fatal error: Cannot redeclare class.

At this point of error, the script terminates.

Recently, one of our customers approached us with this error. So we suggested him to avoid using already existing class in further coding.

But the new class created by our customer was also giving the same error. So, we provided him the below command to fix the problem.

Here XXXX is the new class name.

2. Cannot redeclare class error in WordPress

Sometimes, WordPress sites show fatal error cannot redeclare class.

Usually, PHP based WordPress site shows this error after installation of new plugins or themes. A typical error message in WordPress looks like:

php fatal error cannot redeclare class in WordPress

Support Team checks for the reason for the error.

In most cases, the error will be with the usage of the same class in function.php and plugin files. So, to fix this error we disable the plugin and install the latest version.

[Need help in fixing PHP fatal errors? – We’ll help you.]

Conclusion

In short, PHP fatal error cannot redeclare class occurs due to reuse of an already existing class name, or plugins in WordPress sites. Today, we saw how our Support Engineers fix this error for our customers.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

Источник

Fatal error: Cannot redeclare class CLASSNAME error already tried require_once()

I’m coming from Java programming and I’m trying to apply my knowledge in OOP style programming in PHP. So, I tried to create a utility class to connect to database just like how I usually do it in Java where I create a static method to get the database connection. However, after spending hours I still can’t fix the error. DBHelper.php

db_host, $this->db_user, $this->db_pass, $this->db_name); /* check connection */ if (mysqli_connect_errno()) < printf("Connect failed: %s\n", mysqli_connect_error()); exit(); >return $mysqli_instance; > > ?> 

There are no errors in this file Then I tried to use it on another file called login.php login.php

 Username value: " . $username; echo "
Password value: " . $password; > if (empty($username) || empty($password) ) < echo "Fill out the fields!"; >else < //PREPARE THE PreparedStatment or Stored Procedure $dbHelper = new DBHelper(); $connection = $dbHelper->obtainConnection(); $preparedStatement = $connection->prepare('CALL getUserRoleByLogin(?, ?)'); //getUserRoleByLogin() is the name of stored proc in mysql db $preparedStatement->bind_param('ss', $username, $password); //assign arguments to ? ? $preparedStatement->execute();//execute the stored procedure. This will return a result $userRole = $preparedStatement->store_result(); $countOfRows = $preparedStatement->num_rows; ?>

I read every related question about the Fatal error: Cannot redeclare class CLASSNAME error. I tried following the instructions given by many which is to use require_once(«DBHelper.php»); instead of include(«DBHelper.php»); but still can’t get rid of the error. I tried making the obtainConnection() static and called it via DBHelper::obtainConnection(); but with no luck. Same error message. I get the error on opening brace of class DBHelper < I hope you can help me with this. Thank you.

Источник

Оцените статью