TIL – Access Object Properties via Variable
Blog

TIL – Access Object Properties via Variable

I have been struggling hard since morning as I try to figure out something that was pretty simple in the end . The goal was to create a node object by adding the node field object properties dynamically. Everything looked fine but still it was not adding up.

After burning nearly 4 hours I figured out what was wrong and now it seriously makes me feel like a noob :(

So lets say we have an object $obj which has a property test. So basically to put in data in the object we can access it like this and put in the value.

$obj->test = "Blah Blah!!"

But in my case I needed to insert the data accessing the property via a variable. I was trying to go about it like :

$obj->test = "Blah Blah!!"

And was getting error of illegal string offset.

After having tried to make it work in innumerable ways that went in vain, I finally got the solution.

What I had to do was to wrap the variable to make it accessible by the object.

So the proper working way came around as this:

$obj->{$test} = "Blah Blah!!"

Again, feeling like a noob in PHP programming after this. But it feels great because there is always something to learn everyday. #FeelingOptimistic :)

Reference :
http://stackoverflow.com/questions/3515861/how-can-i-access-an-object-property-named-as-a-variable-in-php
https://imalabya.wordpress.com/2015/04/10/til-access-object-properties-via-variable