如何动态编写PHP对象属性名称?

时间:2022-03-18 15:29:02

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,以便它可以输出正确的值。关于如何处理这个问题的想法?

5 个解决方案

#1


120  

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.

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 0 of the property whose name is given in $field"? The braces allow you to be explicit.

考虑初始代码$ obj - > $ field [0] - 这是否意味着“访问其名称在$ field [0]中给出的属性”,或“访问具有其名称在的属性的键0的元素” $场“?大括号允许你明确。

#2


18  

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]}

#3


8  

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->myprop that property obviously does not exists in the class. That is where __get is called. __get looks up the name in the field array and returns the correct value.

说明:所有字段数据都存储在数组中。当您访问$ myobj-> myprop时,该类中的属性显然不存在。这就是调用__get的地方。 __get在字段数组中查找名称并返回正确的值。

#4


0  

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!

#5


-5  

With Inheritance. for Example:

继承。例如:

YourClass extends stdClass {
   public function YourClass() {
      $this->AnyProperty="any";
   }
}

Now AnyProperty is Dynamically Declared.

现在AnyProperty被动态声明。

#1


120  

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.

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 0 of the property whose name is given in $field"? The braces allow you to be explicit.

考虑初始代码$ obj - > $ field [0] - 这是否意味着“访问其名称在$ field [0]中给出的属性”,或“访问具有其名称在的属性的键0的元素” $场“?大括号允许你明确。

#2


18  

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]}

#3


8  

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->myprop that property obviously does not exists in the class. That is where __get is called. __get looks up the name in the field array and returns the correct value.

说明:所有字段数据都存储在数组中。当您访问$ myobj-> myprop时,该类中的属性显然不存在。这就是调用__get的地方。 __get在字段数组中查找名称并返回正确的值。

#4


0  

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!

#5


-5  

With Inheritance. for Example:

继承。例如:

YourClass extends stdClass {
   public function YourClass() {
      $this->AnyProperty="any";
   }
}

Now AnyProperty is Dynamically Declared.

现在AnyProperty被动态声明。