how to avoid collision of objects ??

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
User avatar
PHPycho
Forum Contributor
Posts: 336
Joined: Fri Jan 06, 2006 12:37 pm

how to avoid collision of objects ??

Post by PHPycho »

Hello forums!!
Suppose we had the following classes:

Code: Select all

class A{
    var $obj_array = array();
    function setObject($classB_obj){
        $this->obj_array[] = $classB_obj
    }
}
 
class B{
    var $id;
    var $name;
    function B($id, $name){
        // necessary initialisation
    }
}
Case:
I would like to set objects as:

Code: Select all

$objA->setObject(new B(1, "x"));
$objA->setObject(new B(2, "y"));
My Question:
How to make the property $obj_array to hold the class objects of B with unique id.

Thanks in advance for the kind help.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: how to avoid collision of objects ??

Post by Chris Corbyn »

Not 100% what you're asking, but is this what you mean?

Code: Select all

class A{
    var $obj_array = array();
    function setObject($classB_obj){
        $this->obj_array[$classB_obj->id] = $classB_obj;
    }
}
anto91
Forum Commoner
Posts: 58
Joined: Mon Mar 10, 2008 10:59 am
Location: Sweden

Re: how to avoid collision of objects ??

Post by anto91 »

@up: its a sample class

@thread: try using array_key_exists on the obj name?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: how to avoid collision of objects ??

Post by John Cartwright »

Chris Corbyn wrote:Not 100% what you're asking, but is this what you mean?

Code: Select all

class A{
    var $obj_array = array();
    function setObject($classB_obj){
        $this->obj_array[$classB_obj->id] = $classB_obj;
    }
}
Using his example he passes a name holder to identify the object, so I've just modified it slightly (same concept)

Code: Select all

class A{
    var $obj_array = array();
    function setObject($classB_obj, $namespace){
        if (array_key_exists($namespace, $this->obj_array)) {
            //handle error that namespace already used
        }
        $this->obj_array[$namespace] = $classB_obj;
    }
}
Post Reply