如何动态编写PHP对象属性名称? [英] How do I dynamically write a PHP object property name?

查看:190
本文介绍了如何动态编写PHP对象属性名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码中具有如下所示的对象属性:

I have object properties in my code that look like this:

$obj ->field_name_cars[0];
$obj ->field_name_clothes[0];

问题是我有100多个字段名称,需要动态写入属性名称.否则,对象名称和属性的键将始终相同.所以我尝试了:

The problem is I have 100s of field names and need to write the property name dynamically. Otherwise, the object name and the keys for the property will always be the same. So I tried:

$obj -> $field[0];

希望属性名称可以动态更改并访问正确的值.但是,我不断在stdClass :: $ field;中获取'undefined property $ field;

Hoping that the name of the property would dynamically be changed and access the correct values. But, I keep getting 'undefined property $field in stdClass::$field;

我或多或少尝试在执行之前动态编写php,以便它可以输出适当的值.关于如何解决这个问题的想法?

More or less I am trying dynamically write the php before it executes so that it can output the proper values. Thoughts on how to approach this?

推荐答案

PHP 7.0更新

PHP 7引入了更改间接变量的方式和属性在解析器级别进行处理(有关更多详细信息,请参见相应的RFC ) .这使实际行为更接近于预期,这意味着在这种情况下$obj->$field[0]将产生预期的结果.

Update for PHP 7.0

PHP 7 introduced changes to how indirect variables and properties are handled at the parser level (see the corresponding RFC for more details). This brings actual behavior closer to expected, and means that in this case $obj->$field[0] will produce the expected result.

在不需要(现在已改进)默认行为的情况下,仍然可以使用花括号将其覆盖,如下所示.

In cases where the (now improved) default behavior is undesired, curly braces can still be used to override it as shown below.

这样写访问权限:

$obj->{$field}[0]

每当变量变量引起歧义时,这种用大括号括起来"的技巧就可以在PHP中使用.

This "enclose with braces" trick is useful in PHP whenever there is ambiguity due to variable variables.

考虑初始代码$obj->$field[0] -这是否意味着访问其名称在$field[0]中给出的属性",或访问其属性在其$field中给出的属性的键0的元素" ?花括号可以使您显得露骨.

Consider the initial code $obj->$field[0] -- does this mean "access the property whose name is given in $field[0]", or "access the element with key 0 of the property whose name is given in $field"? The braces allow you to be explicit.

这篇关于如何动态编写PHP对象属性名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆