0

我创建了一个实体类,我现在想通过将关联数组传递给它来构造它。目标是最终关联数组中的每个键都以“set_”开头,以便对关联数组中的每个值调用适当的设置方法。

foreach($array AS $key => $value)
{
    if(is_string($value))
    {
        eval( '$this->set_'.$key.'(\''.$value.'\');' );
    }
    elseif(is_array($value))
    {
        eval( '$this->set_'.$key.'('.$value.');' );
    }
}

上面的代码适用于 $array 中的元素,其中 $value 是一个字符串或一个 int,但它不适用于数组。

这种方法感觉很笨拙,有没有更好的方法来做到这一点?

提前致谢..

4

2 回答 2

3

看看__set()魔术方法和call_user_func()。这是如何以更优雅的方式完成的可能解决方案之一:

class Entity {

    private $foo;
    private $bar;

    public function __construct(Array $params) {
        foreach($params as $key => $value) {
            $method = 'set_' . $key;
            if(is_callable(array($this, $method))) {
                call_user_func(array($this, $method), $value);
            }
        }
    }

    public function set_Foo($value) {
        $this->foo = $value;
    }

    public function set_Bar($value) {
        $this->foo = $value;
    }

}
于 2013-07-30T19:59:11.727 回答
2

评估可能很危险,请参阅:http ://www.php.net/manual/en/function.call-user-func-array.php

$Function = "set_$key";
call_user_func_array(array($this, $Function), array($Value));

$this 正在调用自己,因为这听起来像是在一个类中使用。

我会使用 array_walk_recursive 来触发这些。

于 2013-07-30T20:06:49.110 回答