I had a scenario at work today that need me to use a variable in an object and call it like I would when using keys in an array.
Like when I have an array, I would do something like this:
$foo = array("apple" => "Hello World!"); $bar = "apple"; echo $foo[$bar]; //OUTPUT: Hello World! |
I was able to use a variable for an object property by simply using $variable.
$obj = new stdClass(); $obj->bar= 'Hello World!'; $foo = "bar"; echo $obj->$foo; //OUTPUT: Hello World! |
I thought it would spit out an error. But it didn’t
i think it’s the same way we use to write code for the “magic” methods __set()/__get() in a class, but used from an out-of-the-class perspective, isn’t it?
@seralf yup I was chatting with my friend about this. And then the __set()/__get magic methods popped out of my head.
Sure it works
$o = new StdClass();
$o->{"var" . substr("variable", 3)} = 'value';
echo $o->variable; // outputs: "value"
Stop using that in examples, it encourages deadshits to use it thus creating even more unmaintainable code!
It is needed at some points, so why not give the coder the tools and let him decide what’s best for him?