views:

895

answers:

3

Suppose I have an array of a objects of user defined class. Wanted to know how do I extract the elements of the array in PHP.

// class definition
class User
{
public $fname;
public $lname;
}

// array of objects of the class defined above
$objUser1 = new User():
$objUser2 = new User():
$objUser3 = new User():
$objUser4 = new User():

$alUser = array();
$alUser[] = $objUser1;
$alUser[] = $objUser2;
$alUser[] = $objUser3;
$alUser[] = $objUser4;


// trying to iterate and extract values using typcasting - this does not work, what is the alternative.
foreach($alUser as $user)
{
$obj = (User) $user; // gives error - unexpected $user;
}

Thats how I used to do in java while extracting objects from the Java ArrayList, hence thought the PHP way might be similar. Can anyone explain it.

+5  A: 
foreach ($alUser as $user) {
    $obj = $user;
}

Why do you need typecasting for this?

tj111
A: 

PHP is a dynamically typed language. There is no need to cast in most cases.

It is impossible to cast to a User: see PHP's documentation on type juggling and casting.

This example would print "$user is a object (User)" four times.

foreach($alUser as $user) {
    echo '$user is a ' . get_type($user);

    if(is_object($user)) {
        echo ' (' . get_class($user) . ')';

    echo "\n";
}
strager
A: 

It would be nice for example Eclipse PDT to determine the type of object for Code Completion. otherwise you are stuck backtracing, where the array was created and what objects were put into it and then look at the class file to see what functions are available (or temp create a new theObject() to see what methods/properties are available if you know what type of object it is. other times may not be as easy if many objects call functions that create those arrays and objects in them, so have to backtrace to see how those arrays made). Heard a few other IDE's may be able to determine type better like phpEd possibly?

armyofda12mnkeys