Destroying a class

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
tolano
Forum Newbie
Posts: 3
Joined: Wed May 10, 2006 11:17 am

Destroying a class

Post 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!
User avatar
Maugrim_The_Reaper
DevNet Master
Posts: 2704
Joined: Tue Nov 02, 2004 5:43 am
Location: Ireland

Post by Maugrim_The_Reaper »

You need to rename one of the classes. Until PHP gets namespace support (coming in PHP).
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post 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');
(#10850)
tolano
Forum Newbie
Posts: 3
Joined: Wed May 10, 2006 11:17 am

Post by tolano »

Thank you very much!
I didn't know this.
I'll try.
Thank you.
Post Reply