KiddTang's avatar

PHP Object Property contains "array[key]" as property name

I am wonder why I am unable to pass the property name as a variable...

// this is working
$entry->sender_info['name']


// but not this
$field_name = "sender_info['name']";
$entry->{$field_name };
0 likes
7 replies
KiddTang's avatar

Repost the code block, I can't edit the original post (it shows blank...)


// this is working 
$entry->sender_info['name']

// but not this 
$field_name = "sender_info['name']"; 
$entry->{$field_name }; 

Anybody can kindly help me on this?

cviv's avatar

What do you want to achieve from your code?

zachleigh's avatar

My guess is that the brackets are parsed as strings, not as language constructs.

This seems like a very bad idea. Break it up into two variables, the property name and the array key.

$entry->{$property}[$key]
1 like
KiddTang's avatar

@cviv I want to form an array for my form. sender_info[key]... then i convert it into json and store into MySQL json column When i gonna retrieve it, i would like to access it directly via the form input name.

KiddTang's avatar

@zachallia Yup, you're right. This works. However, i need to write extra code to split the name inside and outside the bracket. I fetch the input name for retrieving the current value from DB.

zachleigh's avatar

Rather than store it like this sender_info['name'], maybe try storing it like this sender_info|name. That way you can simply explode the string using the pipe (|).

1 like
KiddTang's avatar

@zachleigh Thanks for your suggestion. I found the laravel backpack actually support the json array conversion at the backend...

I will just use their functionality. :)

Please or to participate in this conversation.