PHP set object properties dynamically

你离开我真会死。 提交于 2019-12-19 12:52:43

问题


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


回答1:


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

You can using Reflection, I think.

<?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)



回答2:


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



来源:https://stackoverflow.com/questions/21336747/php-set-object-properties-dynamically

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!