-1

Sorry, its a simple question but difficult for me as I am a new php developer. I have an array $thread_template, which is generated dynamically. When I print this array using print_r function, it gives

 BP_Messages_Thread_Template Object
(
    [current_message] => 3
    [message_count] => 4
    [message] => stdClass Object
        (
            [id] => 73 // I want to get this id.
            [thread_id] => 63
            [sender_id] => 289
            [subject] => Re: This is an anonymous message about a dino
            [message] => this message is second reply from family member.
            [date_sent] => 2014-05-05 13:25:10
            [anonymous] => 
        ) .... and so on

I want to get get id at line# 6. I am using

$thread_template->$message->id;

I also used

$thread_template[message][id];

both are not working. How can I get an id?

David
  • 15,894
  • 22
  • 55
  • 66
Riz
  • 185
  • 3
  • 7
  • 14
  • Try `$thread_template->message->id;` – Ravi Dhoriya ツ May 05 '14 at 13:36
  • 2
    As a first step, [enable error reporting](http://stackoverflow.com/a/6575502/1438393). And you don't include `$` when accessing property values. Just use `$thread_template->message->id`. – Amal Murali May 05 '14 at 13:36
  • 1
    You're dealing with objects, not arrays – Ejaz May 05 '14 at 13:37
  • Glad we could help you. If you feel an answer solved your problem, please [mark it as 'accepted'](https://stackoverflow.com/help/accepted-answer) by clicking the green check mark. – Nic Wortel May 05 '14 at 14:09

2 Answers2

2

First of all, you are not dealing with an array, but with an object ($thread_template), and you're trying to access one of it's properties. You don't need the dollar sign ($) to access property names.

So, assuming that the properties are public, use:

$thread_template->message->id;

(If they're not public, you'll need to use a method that returns the value of the property. Without looking at the code, I can't tell you wether that's the case and if so, which method you need to use)

As you might have noticed by now, the object $thread_template contains a number of properties, including message that is an object of itself, too. The message object contains a number of properties as well, including the id property (which is the one we're looking for).

Is there a situation where I should use a dollar sign in property names?

Only if you want to call a property whose name is saved in a variable. For instance:

$propertyName = 'fooBar';
echo $myObject->$propertyName;

is the same as:

echo $myObject->fooBar;

(but this is just a sidenote, normally you won't have to do this)

Nic Wortel
  • 11,155
  • 6
  • 60
  • 79
1

It's not an array, it's an object, try:

$thread_template->message->id
Ian
  • 3,539
  • 4
  • 27
  • 48