Page 1 of 1

Get object reference from an array of objects.

Posted: Sun Feb 01, 2009 7:22 am
by omb10
pickle | Please use [ code=php ], [ code=text ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.


Hi All,

i have a question about object reference stored in an array.

i have the following code

Code: Select all

 
Class A {
function method1 {
// do something.
}
$obj1 = new A();
$obj2 = new A();
$arr = array();
$arr[0] = $obj1;
$arr[1] = $obj2;
 
foreach ( $arr as $obj) {
$obj->method1();
// why this line does not work??
}
 
why when i store an object of type A in an array i m not able to retrieve it as an A object??
how can i make it return an object of type A.
I came from a java background where this kind of reference works fine.

Thanks in advance.


pickle | Please use [ code=php ], [ code=text ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.

Re: Get object reference from an array of objects.

Posted: Sun Feb 01, 2009 8:10 am
by mickeyunderscore
I tested your code and if you posted exactly what you were using then it wouldn't have worked because of syntax errors, I changed it slightly and it's working fine for me now:

Code: Select all

 
Class A {
    function method1() {
        echo "test";
    }
}
$obj1 = new A();
$obj2 = new A();
$arr = array();
$arr[0] = $obj1;
$arr[1] = $obj2;
 
foreach ( $arr as $obj) {
    $obj->method1();
   //outputs test
}