简体   繁体   中英

PHP Object Variable variables name?

I have a loop that goes from 1 to 10 and prints values in

$entity_object->field_question_1 through 10 so...

$entity_object->field_question_1 , $entity_object->field_question_2 , etc

And I want to print this in this loop, how can I get the variable? I tried doing the

$var = "entity_object->field_question_".$i;
print $$var;

But that did not work...

How can I get these values?

This should work:

$var="field_question_$i";
$entity_object->$var;

Actually you need to take the variable outside the string like this in order to those solutions to work: $var="field_question_".$i;

$entity_object->$var;

Or

$entity_object->{"field_question_".$i}

First of all, arrays are more suitable for what you want to do.

The answer to you question: print $entity_object->{"field_question_$i"};

When upgrading to PHP 7 we faced an issue with statements like:

$variable->$node[$i] = true;

That worked perfectly fine in PHP 5.4 but in PHP 7 caused the entire website to crash. So we replace it with:

$variable->{$node[$i]} = true;

To solve the problem.

Or you can typecast between arrays and objects.

Array's are simple in the fact that they are organized and easily accessed. Objects are quite the differ but off many pro's.

Set your objects like so:

$entity_object["field_question_{$i}"] = ''//value;

They can then be typecasted to an object:

$entity_object = (object)$entity_object;

You would then reference them like:

$entity_object->field_question_1 ...;

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