G-J
G-J

Reputation: 1068

Can I use a Variable to access the property name of an object?

Let's assume I have the following...

$current_user->ID = 3;

Let's also assume I have the following...

$read = $recipient->read_3;

Note that that the number in the $recipient->read_ property name can change so I don't actually know there is a $recipient->read_3;. I want get the name (e.g. 3) from the value of $current_user->ID to add to $recipient->read_ to get the correct property name.

How do I do that?

I would love to do this... $read = $recipient->read_$current_user->ID; but that is not correct... What is correct?

Upvotes: 1

Views: 45

Answers (3)

FluffyKitten
FluffyKitten

Reputation: 14312

You could use try using PHP variable variables. These let you create dynamic variables so you can do this:

$propname = "read_".$current_user->ID;
$read = $recipient->{$propname};

You can find out more about variable variables here: PHP.net variable variables

Upvotes: 0

G-J
G-J

Reputation: 1068

Based on the answer from @majed-badawi I came up with the following:

$num = "read_".$current_user->ID;

$read = $recipient->$num;

Upvotes: 0

Majed Badawi
Majed Badawi

Reputation: 28414

You can save it in a variable and use it. Here is an example:

$object = new stdClass();
$object->read_3 = '3';
$id = 3;
$read = 'read_'.$id;
echo $object->$read;

Output:

3

Upvotes: 1

Related Questions