views:

110

answers:

4

I have two class named test in two different files,a.php and b.php for instance,the logic is like this:

include('a.php');
$a = new test();
if($somcondition_is_met)
{
    include('b.php');
    $b = new test();
}

Is there some trick to avoid Fatal error: Cannot redeclare class ?

A: 

classkit_import() looks like it does exactly what you want

http://www.php.net/manual/en/function.classkit-import.php

From the link:

Example #1 classkit_import() example

newclass.php

<?php
class Example {
    function foo() {
        return "bar!\n";
    }
}
?>

main.php

<?php
// requires newclass.php (see above)
class Example {
    function foo() {
        return "foo!\n";
    }
}

$e = new Example();

// output original
echo $e->foo();

// import replacement method
classkit_import('newclass.php');

// output imported
echo $e->foo();

?>

The above example will output: foo! bar!

Robert
A: 

With "standard" PHP, no, you cannot do such a thing.


Still, looking at PECL and the manual, a possibility would be to use the classkit extension -- but it's marked as "not maintained", and has not been updated since 2004... So I would definitly not use it.

Quoting the PECL's page of that extension :

NOTICE: This package has been discontinued. Please refer to the runkit package which is fully BC with classkit and contains additional functionality.


So, let's take a look at the runkit extension, which might do the trick -- especially, the runkit_import function could interest you (quoting) :

Similar to include() however any code residing outside of a function or class is simply ignored. Additionally, depending on the value of flags , any functions or classes which already exist in the currently running environment will be automatically overwritten by their new definitions.

Still, note that, officially (looking at it's PECL page), the runkit extension has not been updated since 2006... Which is not a good sign either... Especially when it comes to PHP 5.3 support...

Pascal MARTIN
A: 

I think it is better to use Interfaces, rather then overwriting classes dynamicaly.

In your code you reference/use the interface class, and than you can have multiple classes that implement that interface.

Check the doc for more details on interfaces. http://php.net/manual/en/language.oop5.interfaces.php