PHP Object Variable 变量名?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10919011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:21:20  来源:igfitidea点击:

PHP Object Variable variables name?

php

提问by Steven

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

我有一个从 1 到 10 的循环并在

$entity_object->field_question_1through 10 so...

$entity_object->field_question_1通过 10 所以...

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

$entity_object->field_question_1$entity_object->field_question_2

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?

我怎样才能得到这些值?

回答by Tim Withers

This should work:

这应该有效:

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

回答by user1830966

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

实际上,您需要像这样将变量放在字符串之外,以便这些解决方案起作用: $var="field_question_".$i;

$entity_object->$var;

$entity_object->$var;

Or

或者

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

回答by Samy Dindane

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

首先,数组更适合你想做的事情。

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

你问题的答案: print $entity_object->{"field_question_$i"};

回答by cjohansson

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

升级到 PHP 7 时,我们遇到了以下语句的问题:

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

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

这在 PHP 5.4 中运行良好,但在 PHP 7 中导致整个网站崩溃。所以我们将其替换为:

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

To solve the problem

解决问题

回答by Mike Mackintosh

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 ...;