Cannot redeclare class + class not found? - php

I have had some really strange errors here with php today.
I've written a little class for A/B Testing and wanted to create a new instance in a php document of mine:
if(!class_exists('ab_tester')) include('../lib/php/ab_tester.php');
$ab = new ab_tester($user['id']);
One would think this should do the trick, but php says:
Fatal error: Cannot redeclare class ab_tester in [PATH_TO_PHP]ab_tester.php on line 10
Why does this happen?
Note: Line 10 of the ab_tester.php looks like this:
class ab_tester {
If I leave the include line out, creating a new instance of ab_tester, it spits out:
Fatal error: Class 'ab_tester' not found in [PATH_TO_PHP]returning.php on line 25
What do I do now? If I try to import it, it's already there and if I don't, its missing.

And what do the first 9 lines of code in ab_tester.php contain?
I bet that there is another class ab_tester there (or in an include, anyway)
EDIT:
Another possible explanation is that you are doing a second include of ab_tester.php later on the code of returning.php. So even if you use include_once in this particular line, the second call is still just an include...

How about:
include_once('../lib/php/ab_tester.php');
$ab = new ab_tester($user['id']);
?

Try autoloading classes instead of using includes?
function __autoload($class_name){
$class_name = strtolower($class_name);
$path = "../includes/{$class_name}.php";
if(file_exists($path)){
require_once($path);
}else{
die("The file {$class_name}.php could not be found.");
}
}

Related

PHP - Fatal error: Cannot redeclare class Config in /path/to/Config.php on line 44

This is a WordPress local installation that I am trying to work with. I have not written a single line of this code myself. I don't understand what this error means:
Fatal error: Cannot redeclare class Config in /Applications/XAMPP/xamppfiles/lib/php/Config.php on line 44
Line 44 reads as follows:
class Config {
My guess is that a Config class has either already been declared elsewhere, or that this file is being executed for the second time.
That usually happens when you declare a class more than once in a page -- maybe via multiple includes.
To avoid this, use require_once instead. If you use require_once PHP will check if the file has already been included, and if so, not include (require) it again.
Say, for example, you have the following code:
<?php
class foo {
# code
}
... more code ...
class foo { // trying to re-declare
#code
}
In this case, PHP will throw a fatal error similar to the one below:
Fatal error: Cannot redeclare class foo in /path/to/script.php on line 7
In this case it's very simple -- simply find the 7th line of your code and remove the class declaration from there.
Alternativey, to make sure you don't try to re-declare classes, you can use the handy class_exists() function:
if(!class_exists('foo')) {
class foo {
# code
}
}
The best approach, of course, would be to organize all the configurations in one single file called config.php and then require_once it everywhere. That way, you can be sure that it will be included only once.
As for debugging the error, you could use debug_print_backtrace().
It's possible that the theme you are using refers to a file called config.php. If so use the following steps.
Try to find the config.php file and change it's name to configuration.php.
Find the files where they use config.php in the code and change it to configuration.php.

strange Fatal error: Cannot redeclare class paradox [duplicate]

Does anyone know what can cause this problem?
PHP Fatal error: Cannot redeclare class
You have a class of the same name declared more than once. Maybe via multiple includes. When including other files you need to use something like
include_once "something.php";
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.
It means you've already created a class.
For instance:
class Foo {}
// some code here
class Foo {}
That second Foo would throw the error.
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().
if (!class_exists('TestClass')) {
// Put class TestClass here
}
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.
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
I had the same problem while using autoload like follows:
<?php
function __autoload($class_name)
{
include $class_name . '.php';
}
__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.
Just adding;
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 '<pre>';
$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 '</pre>';
}
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.
Did You use Zend Framework? I have the same problem too.
I solved it by commenting out this the following line in config/application.ini:
;includePaths.library = APPLICATION_PATH "/../library"
I hope this will help you.
Another possible culprit is source control and unresolved conflicts. SVN may cause the same class to appear twice in the conflicted code file; two alternative versions of it ("mine" and "theirs").
I have encountered that same problem:
newer php version doesn't deal the same with multiple incluse of the same file (as a library), so now I have to change all my include by some include_once.
Or this tricks could help, if you d'ont have too much class in your library...
if( class_exists('TestClass') != true )
{
//your definition of TestClass
}
I had the same problem "PHP Fatal error: Cannot redeclare class XYZ.php".
I have two directories like controller and model and I uploaded by mistakenly XYZ.php in both directories.(so file with the same name cause the issue).
First solution:
Find in your whole project and make sure you have only one class XYZ.php.
Second solution:
Add a namespace in your class so you can use the same class name.
It actually means that class is already declared in the page and you are trying to recreate it.
A simple technique is as follow.
I solved the issue with the following. Hope this will help you a bit.
if(!class_exists("testClassIfExist"))
{
require_once("testClassIfExist.php");
}
i have encountered that same problem. found out the case was the class name. i dealt with it by changing the name. hence resolving the problem.
You must use require_once() function.

Redeclaring a class (in a lower directory)

I have the following error
Fatal error: Cannot redeclare class Database in /home/content/63/8026363/html/include/user_database.php on line 5
That links to the line
class Database
But I have not redeclared this anywhere I can see.
I've checked all the include files and still can't see it.
I have now changed the name to user_database1.php which is DEFINITELY only included once in my WHOLE system and I am still getting the same message!
This only occurs in my root/admin directory.
When I moved the file it occurs into the root directory and updated the include files from ../file.php to just file.php, it worked perfectly.
I can't understand why having the file.php in the /admin directory and using ../ to include files isn't working!
Can anyone offer any experience of this? Or a potential fix.
I'll provide some code from the top of the file in question..
<?php
include("../include/session.php");
include("../include/admin_database.php");
Clearly this is the problem but I can't understand why!
Hope someone can help !
(question has been updated significantly since a lot of the answers below were submitted)
If you included the file two times, theen it gets re-declared. Use include_once() instead to prevent that easily.
If you are unsure where that class was originally declared, you can make use of the Reflection API to get the name of the file and the line of code:
$class = 'Database';
if(class_exists($class))
{
$oRefl = new ReflectionClass($class);
$message = sprintf('Class %s already defined in %s on line %s.', $class, $oRefl->getFileName, $oRefl->getStartLine);
throw new DomainException($message);
}
Place that before the line where you define the class Database to find out which file was originally defining the class.
Check if php already defines a file called Database.php.
Maybe you are using some framework or library which does.
You probably have included your database class more than once, a quick fix for this is to add something like this to the top of your class:
if(!class_exists('Database')){
class Database{
// so on
}
This ensures that your class is only defined once.

Using spl_autoload() not able to load class

I'm playing around with the SPL autoload functionality and seem to be missing something important as I am currently unable to get it to work. Here is the snippet I am currently using:
// ROOT_DIRECTORY translates to /home/someuser/public_html/subdomains/test
define('ROOT_DIRECTORY', realpath(dirname(__FILE__)));
define('INCLUDE_DIRECTORY', ROOT_DIRECTORY . '/includes/classes/');
set_include_path(get_include_path() . PATH_SEPARATOR . INCLUDE_DIRECTORY);
spl_autoload_extensions('.class.php, .interface.php, .abstract.php');
spl_autoload_register();
When I echo get_include_path() I do get the path I expected:
// Output echo get_include_path();
.:/usr/lib/php:/usr/local/lib/php:/home/someuser/public_html/subdomains/test/includes/classes/
However when I run the code I get this error message:
Fatal error: spl_autoload() [function.spl-autoload]: Class Request could not be loaded in
/home/someuser/public_html/subdomains/test/contact.php
on line 5
Request.class.php is definitely in the /home/someuser/public_html/subdomains/test/includes/classes/ directory.
What am I missing?
There is a comment (anonymous) on http://www.php.net/manual/en/function.spl-autoload-register.php#96804 that may apply to your problem: spl_autoload_register() doesn't seem to play nice with camelcase, and in your case could be trying to find request.class.php instead of Request...
The path where the class is supposed to be seems not to match the path were you expect them. Compare
.:/usr/lib/php:/usr/local/lib/php:/home/someuser/public_html/subdomains/test/includes/classes/
with
/home/someuser/public_html/subdomains/test/
The difference is, that your class is not in includes/classes/ as your SPL requires it but a few directories above.
I got a similar error message but my issue was different. My error message looked like
PHP Fatal error: spl_autoload(): Class Lib\Lib\Regex could not be loaded in /dir1/dir2/lib/regex.php on line 49
It turned out I forgot to remove the Lib\ from Lib\Regex inside the Regex class definition itself. I had something like the following:
namespace Lib;
class Regex {
...
public static function match($pattern, $str) {
$regex = new Lib\Regex($pattern);
...
}
}

PHP Fatal error: Cannot redeclare class

Does anyone know what can cause this problem?
PHP Fatal error: Cannot redeclare class
You have a class of the same name declared more than once. Maybe via multiple includes. When including other files you need to use something like
include_once "something.php";
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.
It means you've already created a class.
For instance:
class Foo {}
// some code here
class Foo {}
That second Foo would throw the error.
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().
if (!class_exists('TestClass')) {
// Put class TestClass here
}
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.
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
I had the same problem while using autoload like follows:
<?php
function __autoload($class_name)
{
include $class_name . '.php';
}
__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.
Just adding;
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 '<pre>';
$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 '</pre>';
}
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.
Did You use Zend Framework? I have the same problem too.
I solved it by commenting out this the following line in config/application.ini:
;includePaths.library = APPLICATION_PATH "/../library"
I hope this will help you.
Another possible culprit is source control and unresolved conflicts. SVN may cause the same class to appear twice in the conflicted code file; two alternative versions of it ("mine" and "theirs").
I have encountered that same problem:
newer php version doesn't deal the same with multiple incluse of the same file (as a library), so now I have to change all my include by some include_once.
Or this tricks could help, if you d'ont have too much class in your library...
if( class_exists('TestClass') != true )
{
//your definition of TestClass
}
I had the same problem "PHP Fatal error: Cannot redeclare class XYZ.php".
I have two directories like controller and model and I uploaded by mistakenly XYZ.php in both directories.(so file with the same name cause the issue).
First solution:
Find in your whole project and make sure you have only one class XYZ.php.
Second solution:
Add a namespace in your class so you can use the same class name.
It actually means that class is already declared in the page and you are trying to recreate it.
A simple technique is as follow.
I solved the issue with the following. Hope this will help you a bit.
if(!class_exists("testClassIfExist"))
{
require_once("testClassIfExist.php");
}
i have encountered that same problem. found out the case was the class name. i dealt with it by changing the name. hence resolving the problem.
You must use require_once() function.

Categories