doucan9079 2012-05-28 19:05
浏览 39
已采纳

PHP - 使用数组参数初始化对象成员

Is it possible to initialize an objects private or protected members in php with an associative array.

for example:

    class TestClass
{
    public $_name;
    public $_age;


    public function __construct(array $params)
    {
        ??????
    }
}


$testClass = new TestClass(
    array(
        'name'  => 'Bob',
        'age' => '29',
    )
);

i was wondering whether there is an elegant solution - perhaps by implementing one the spl interfaces or otherwise?

  • 写回答

2条回答 默认 最新

  • doufu7835 2012-05-28 20:51
    关注

    You mentioned SPL. But without knowing the exact requirements for the purpose of your object, the below is about the only information I can give...

    You could have your object extend the SPL built-in class ArrayIterator. Then, without concern for handling it in the constructor (already handled in the parent ArrayIterator class), you could import an array into your object simply like so:

    class testClass extends ArrayIterator
    {
    
     /* child '__construct' method not required */
    
     /* rest of your code here */
    
    }
    
    $t = new testClass(array('name' => 'asdf', 'age' => 99));
    

    Keep in mind that with default ArrayIterator behavior, you cannot later access any of the passed array values as you would with a normal object property. You must access them as you would an array:

    echo $t['name']; // 'asdf'
    echo $t->name; // NULL property unknown error
    

    And, internally, the passed array is stored within your object as a single private storage parameter. In your case, you already have all your object properties pre-defined and prepended with an underscore, so you would probably have to manually loop over $this or $params anyway in your constructor to set any real object properties.

    You could of course redefine all your child object's ArrayIterator inherited methods to handle your special property naming case on get or set, but this would seem redundant and unproductive as opposed to just looping over $params/setting $this anyway in your constructor.

        public function __construct(array $params)
        {
            foreach ($params as $key => $val) {
                if (property_exists($this, "_$key")) {
                    $this->{"_$key"} = $val;
                }
            }
        }
    

    So, just looping over $params/setting $this within your constructor is probably the best, most simple solution there is.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效