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.
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.
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.
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.
You can't.
The feature is called variable properties:
<?php
$myObject = (object)NULL;
$myObject->value_1 = 'I am value nr 1';
$id = 1;
echo $myObject->{"value_$id"};
This works:
$variableName = 'value_whatever_1337';
echo $myObject->$variableName;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With