PHP 动态设置对象属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21336747/
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-25 04:03:47  来源:igfitidea点击:

PHP set object properties dynamically

phpobjectsetter

提问by Ben

I have a function, that should read array and dynamically set object properties.

我有一个函数,它应该读取数组并动态设置对象属性。

class A {
    public $a;
    public $b;

    function set($array){
        foreach ($array as $key => $value){
            if ( property_exists ( $this , $key ) ){
                $this->{$key} = $value;
            }
        }
    }
}

$a = new A();
$val = Array( "a" => "this should be set to property", "b" => "and this also");
$a->set($val);

Well, obviously it doesn't work, is there a way to do this?

好吧,显然它不起作用,有没有办法做到这一点?

EDIT

编辑

It seems that nothing is wrong with this code, the question should be closed

这段代码好像没什么问题,应该关闭问题

采纳答案by CentaurWarchief

http://www.php.net/manual/en/reflectionproperty.setvalue.php

http://www.php.net/manual/en/reflectionproperty.setvalue.php

You can using Reflection, I think.

你可以使用Reflection,我想。

<?php 

function set(array $array) {
  $refl = new ReflectionClass($this);

  foreach ($array as $propertyToSet => $value) {
    $property = $refl->getProperty($propertyToSet);

    if ($property instanceof ReflectionProperty) {
      $property->setValue($this, $value);
    }
  }
}

$a = new A();

$a->set(
  array(
    'a' => 'foo', 
    'b' => 'bar'
  )
);

var_dump($a);

Outputs:

输出:

object(A)[1]
  public 'a' => string 'foo' (length=3)
  public 'b' => string 'bar' (length=3)

回答by Dimitris Bouzikas

You only need to remove brackets {} and will work! -> $this->$key = $value;

您只需要删除方括号 {} 就可以了!->$this->$key = $value;