Page 1 of 1

how to avoid collision of objects ??

Posted: Wed Apr 02, 2008 5:26 am
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.

Re: how to avoid collision of objects ??

Posted: Wed Apr 02, 2008 5:35 am
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;
    }
}

Re: how to avoid collision of objects ??

Posted: Wed Apr 02, 2008 6:17 am
by anto91
@up: its a sample class

@thread: try using array_key_exists on the obj name?

Re: how to avoid collision of objects ??

Posted: Wed Apr 02, 2008 9:55 am
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;
    }
}