tags:

views:

28

answers:

3

Hello,

So the thing is that i'm new to OOP php and i seems can't find answer to how to retrieve specific value from Object array.

So i run my request to the User class and method find_by_sql:

$getAct = User::find_by_sql($sql);

Response i get is:

Array
(
    [0] => User Object
        (
            [id] => 6
            [permissions] => 0
            [email] => [email protected]
            [password] => 918f358a5cdf01e63d4609063d9A2bfec57f8455
            [first_name] => Name
            [last_name] => Surname
            [city] => City
            [gender] => m
            [birth_date] => 1980-02-02
            [act_code] => AAAAAAAAAAAAAAA
        )

)

So my question basically is how can i set [act_code] value to my variable? If i would use non-static method it would be easy since i could just call $obj->act_code. But how do i do same from static method call?

A: 

You have to do

$getAct  = User::find_by_sql($sql);
$actCode = $getAct[0]->act_code;

or more verbose

$getAct  = User::find_by_sql($sql); // returns an array
$user    = $getAct[0];              // assign first element in array to $user
$actCode = $user->act_code;         // read act_code member from User Object

As you can see by your result dump, $getAct contains an Array with one element (as indicated by [0] because Arrays are indexed with zero-based keys). The element is a User Object.

You access/mutate/call Object members/methods with the T_OBJECT_OPERATOR (->). Since $getAct[0] will return a handle to the object, you can then fetch the property by ->get_act.

Gordon
Thanks for answer very in detail. As i'm new i'm not quite aware of all stuff around OOP :)
arma
A: 

To assign the value of the first array element's member variable act_code to a variable:

$act_code = $getAct[0]->act_code;
joschi
A: 

I'm not sure what ORM you are using, but if you want to retrieve only one record, just limit it to 1. That should return a User object instead of an array of User objects

$user = User::find_first_by_sql($sql);
$act  = $user->act_code;`
alfonsojimenez