Solidity: How can I access a variable dynamically by name?

217 Views Asked by At

Is there a way to access variables in solidity using another variable?

Something like this:

contract Test {
    uint age;
    string varAge = "age";

    function setAge() public {
        // varAge should be able to access age variable
       ${varAge} = 30;
    }
}
1

There are 1 best solutions below

0
On

No. It's not like PHP.

The closest thing I can think of is having a mapping like mapping(string=>uint) myMap;. Then you can do stuff like myMap["abc"] = 123;

You could also do this...

uint key = "abc";
myMap[key] = 123;