简体   繁体   中英

when using variable: Fatal error: Cannot use string offset as an array

The following piece of code:

$field = 'field_total_comments_added';
$current_user_count = $user_data->$field['und']['0']['value'];

returns an error: Fatal error: Cannot use string offset as an array

if I just use:

$current_user_count = $user_data->field_total_comments_added['und']['0']['value'];

the code works just fine. In order to use some custom functionality I have to use the variable displayed in the first code block. How can I solve this?

Please tell me if the problem isn't clear to you.

Thanks in advance for your assistance

You can use this common workaround:

$current_user_count = $user_data->{$field}['und']['0']['value'];

Which basically forces the variable property name to have precedence over the array access operator.

Try:

$field = 'field_total_comments_added';
$current_user_count = ($user_data->$field)['und']['0']['value'];

It might only work for PHP 5.4. For earlier versions, also try:

$field = 'field_total_comments_added';
$item = $user_data->$field;
$current_user_count = $item['und']['0']['value'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM