如何动态编写 PHP 对象属性名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12571197/
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
How do I dynamically write a PHP object property name?
提问by user658182
I have object properties in my code that look like this:
我的代码中有对象属性,如下所示:
$obj ->field_name_cars[0];
$obj ->field_name_clothes[0];
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:
问题是我有 100 个字段名称,需要动态编写属性名称。否则,对象名称和属性的键将始终相同。所以我试过:
$obj -> $field[0];
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;
希望属性的名称可以动态更改并访问正确的值。但是,我一直在 stdClass::$field 中收到 'undefined property $field;
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,以便它可以输出正确的值。关于如何处理这个问题的想法?
回答by Jon
Update for PHP 7.0
PHP 7.0 更新
PHP 7 introduced changes to how indirect variables and properties are handledat the parser level (see the corresponding RFCfor more details). This brings actual behavior closer to expected, and means that in this case $obj->$field[0]will produce the expected result.
PHP 7对在解析器级别处理间接变量和属性的方式进行了更改(有关更多详细信息,请参阅相应的 RFC)。这使实际行为更接近预期,并且意味着在这种情况下$obj->$field[0]将产生预期结果。
In cases where the (now improved) default behavior is undesired, curly braces can still be used to override it as shown below.
在不希望(现在改进的)默认行为的情况下,仍然可以使用大括号来覆盖它,如下所示。
Original answer
原答案
Write the access like this:
像这样写访问:
$obj->{$field}[0]
This "enclose with braces" trick is useful in PHP whenever there is ambiguity due to variable variables.
这种“用大括号括起来”的技巧在 PHP 中每当由于变量变量引起歧义时都很有用。
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 0of the property whose name is given in $field"? The braces allow you to be explicit.
考虑初始代码$obj->$field[0]——这是否意味着“访问名称在$field[0]”中给出的属性,或“访问具有0名称在$field“中给出的属性的键的元素?大括号允许您明确。
回答by Mike Brant
I think you are looking for variable-variable type notation which, when accessing values from other arrays/objects, is best achieved using curly bracket syntax like this:
我认为您正在寻找变量 - 变量类型符号,当访问来自其他数组/对象的值时,最好使用这样的大括号语法来实现:
$obj->{field[0]}
回答by JvdBerg
The magic method __get is you friend:
魔术方法 __get 是你的朋友:
class MyClass
{
private $field = array();
public function __get($name)
{
if(isset($this->field[$name]))
return $this->field[$name];
else
throw new Exception("$name dow not exists");
}
}
Usage:
用法:
$myobj = new MyClass();
echo $myobj->myprop;
Explanation: All your field data is stored in a array. As you access $myobj->mypropthat property obviously does not exists in the class. That is where __getis called. __getlooks up the name in the fieldarray and returns the correct value.
说明:您的所有字段数据都存储在一个数组中。当您访问$myobj->myprop该属性时,该类中显然不存在。这__get就是所谓的。__get在field数组中查找名称并返回正确的值。
回答by Jordan Georgiadis
today i face that challenge. I ended up with that style of development
今天,我面临这一挑战。我最终采用了那种开发方式
$countTickets = new \stdClass;
foreach ($tickets as $key => $value) {
if(!isset($countTickets->total)){
$countTickets->total = 0;
}
if(!isset($countTickets->{$value['categoryname']})){
$countTickets->{$value['categoryname']} = 0;
}
$countTickets->total += $value['number'];
$countTickets->{$value['categoryname']} += $value['number'];
}
回答by Everterstraat
aboulfazl, since PHP 5.3.3 methods with the same name as the class won't be treated as constructor!
aboulfazl,因为与类同名的 PHP 5.3.3 方法不会被视为构造函数!
YourClass
{
public $any = false;
public function __construct($any = null)
{
$this->any = (is_null($any) ? $this->any : $any);
}
}
This works but wasn't ask by the topic owner, Jon gives the awnser!
这有效,但主题所有者没有问,Jon 提供了 awnser!
回答by Peter Schaeffer
I worked on some code that used dynamically created object properties. I thought that using dynamically created object properties was pretty cool (true, in my opinion). However, my program took 7 seconds to run. I removed the dynamic object properties and replaced them object properties declared as part of each class (public in this case). CPU time went from over 7 seconds to 0.177 seconds. That's pretty substantial.
我编写了一些使用动态创建的对象属性的代码。我认为使用动态创建的对象属性非常酷(在我看来是真的)。但是,我的程序运行了 7 秒。我删除了动态对象属性并替换了它们作为每个类的一部分声明的对象属性(在这种情况下是公共的)。CPU 时间从超过 7 秒变为 0.177 秒。这是相当可观的。
It is possible that I was doing something wrong in the way I was using dynamic object properties. It is also possible that my configuration is broken in some way. Of course, I should say that I have a very plain vanilla PHP configuration on my machine.
有可能我在使用动态对象属性的方式上做错了。我的配置也有可能以某种方式损坏。当然,我应该说我的机器上有一个非常简单的普通 PHP 配置。
回答by Boss Andrew
The best way you can use instance of PHP default class Object to dynamically assign properties to it
您可以使用 PHP 默认类 Object 的实例为其动态分配属性的最佳方式
$inst=new \StdClass;
$inst->any_property = '';
回答by aboulfazl
With Inheritance. for Example:
与继承。例如:
YourClass extends stdClass {
public function YourClass() {
$this->AnyProperty="any";
}
}
Now AnyProperty is Dynamically Declared.
现在 AnyProperty 是动态声明的。

