Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve Object array value?

Tags:

arrays

object

php

The thing is that I'm new to OOP PHP and I seem can't find the answer to how to retrieve a specific value from array of objects.

When I run request to the User class and method find_by_sql:

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

The 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
        )

)

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

like image 917
arma Avatar asked Feb 11 '26 20:02

arma


1 Answers

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.

like image 148
Gordon Avatar answered Feb 13 '26 10:02

Gordon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!