设置对象属性的正确方法

时间:2016-11-29 07:16:59

标签: php arrays object methods properties

我知道这个问题有点争议,但无论如何: 让我们说我有一个简单的课程:

class A {
    private $a;
    private $b;

    function __construct($data = array()){
        if($data) $this->setAll($data);
    }

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

    function setAllByFunctions($array){
       foreach ($array as $key => $value){
            $method_name = "set".$key;
            if ( method_exists ( $this ,  $method_name) ){
                $this->$method_name($value);
            }
        }
    }

    function setA($value){
         $this->a = $value;
         return $this;
    }
    function setB($value){
        $this->b = $value;
        return $this;
    }
}

考虑到真正的类可以拥有更多属性,设置对象属性的最佳方法是什么?优缺点都有什么?有没有我能读到的文章?我无法谷歌任何有用的东西。

1)

$a1 = new A();
$val = Array("A" => "value of a", "B" => "value of b");
$a1->setAll($val);

2)

$a2 = new A();
$a2->setA("value of a")->setB("value of b");

3)

$val = Array("A" => "value of a", "B" => "value of b");
$a3 = new A($val);

4)

$a4 = new A($val);
$val = Array("A" => "value of a", "B" => "value of b");
$a1->setAllByFunctions($val);

0 个答案:

没有答案