Get object reference from an array 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
omb10
Forum Newbie
Posts: 3
Joined: Sun Feb 01, 2009 7:09 am

Get object reference from an array of objects.

Post 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.
mickeyunderscore
Forum Contributor
Posts: 129
Joined: Sat Jan 31, 2009 9:00 am
Location: UK

Re: Get object reference from an array of objects.

Post 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
}
 
Post Reply