Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting object variable using string + variable

I would like to do something like this: echo $myObject->value_$id but I don't know proper syntax and I'm not sure if it is possible.

$id is some PHP variable, for example has value 1. In the end, I would like to get $myObject->value_1 but the number part (1) should be dynamic.

like image 452
simPod Avatar asked Dec 28 '11 15:12

simPod


People also ask

Is a string variable an object?

Because s contains a reference to a string, we say that it is an example of a reference type variable (as opposed to a primitve type variable that actually contains its value). Once we create a string, its value cannot be changed. Because of this, we say that strings are immutable objects.

How do you access variables in objects?

Use the member-access operator ( . ) between the object variable name and the member name. If the member is Shared, you do not need a variable to access it.

How do you find the variable name of a string?

To get a variable's name as a string: Use the globals() function to get a dictionary that implements the current module namespace. Iterate over the dictionary to get the matching variable's name. Access the list item at index 0 to get the name of the variable.

Can you use a string to name an object Java?

You can't.


2 Answers

The feature is called variable properties:

<?php

$myObject = (object)NULL;
$myObject->value_1 = 'I am value nr 1';

$id = 1;
echo $myObject->{"value_$id"};
like image 58
Álvaro González Avatar answered Sep 23 '22 16:09

Álvaro González


This works:

$variableName = 'value_whatever_1337';
echo $myObject->$variableName;
like image 33
Armin Avatar answered Sep 25 '22 16:09

Armin