Page 1 of 1

Destroying a class

Posted: Wed May 10, 2006 11:26 am
by tolano
Hi! I have a problem and I don't know how to resolve it.
I have 2 files:
a.php
b.php

In both of them, I have a class called myClass()
I wanted to do something like this:
require_once(a.php)
$x=new myClass()
unset($x)
require_once(b.php)
$x=new myClass()
unset($x)

I thougt that this would work, but there is an error:
Cannot redeclare class myClass
Why? I have done an unset(). Is there any way to do what I want?
What's the problem? I'm becoming crazy.
Thank you very much!

Posted: Wed May 10, 2006 11:54 am
by Maugrim_The_Reaper
You need to rename one of the classes. Until PHP gets namespace support (coming in PHP).

Posted: Wed May 10, 2006 12:22 pm
by Christopher
The problem is not necessarily what you want to do, it is how you want to do it. The pattern for what you want to do is called a Factory and for you it would look something like this:

Code: Select all

class myClass {

function create ($type) {
    $obj = null;
    switch ($type) {
    case 'A'
        require_once(myClassA.php);
        $obj = new myClassA();
        break;
    case 'B'
        require_once(myClassB.php);
        $obj = new myClassB();
        break;
    }
    return $obj;
}
Static usage:

Code: Select all

$obj = myClass::create('A');

Posted: Wed May 10, 2006 12:30 pm
by tolano
Thank you very much!
I didn't know this.
I'll try.
Thank you.