2012-01-05 38 views
4

因为我懒我在想,如果PHP有速记的方法来设置这样的属性...有没有简捷的方法来设置许多对象属性?

with $person_object { 
    ->first_name = 'John'; 
    ->last_name = 'Smith'; 
    ->email = '[email protected]'; 
} 

是否有这样的事?或者,是否有一种懒惰的方式来设置属性,而不必一次又一次地输入$person_object

+0

你可以做一个普通的装饰功能。 – zzzzBov 2012-01-05 18:03:48

回答

8

您可以在Person类中实现类似于构建器模式的东西。该方法涉及在每次setter调用结束时返回$this

$person 
    ->set_first_name('John') 
    ->set_last_name('Smith') 
    ->set_email('[email protected]'); 

而在你的类...

class Person { 
    private $first_name; 
    ... 
    public function set_first_name($first_name) { 
     $this->first_name = $first_name; 
     return $this; 
    } 
    ... 
} 
+0

天才!我喜欢它。谢谢你保持我的懒惰。 – noctufaber 2012-01-05 19:18:08

+1

这是一个不好的破解。不要滥用模式来实现速记! – Pacerier 2014-10-07 14:09:23

2

编号

不,没有。

2

一个普通的装饰功能,可以为你做到这一点:

function decorate($object, $data) 
{ 
    foreach ($data as $key => $value) 
    { 
    $object->$key = $value; 
    } 
} 

decorate($person_object, array('first_name' => 'John', 'last_name' => 'Smith')); 

我可能犯了一些错误,它已经有一段时间因为我写了PHP代码,这是未经测试的

1

不,我不这么认为。但是你可以做这样的事情:

class Person { 

function __call($method, $args) { 
    if (substr($method, 0, 3) == set) { 
     $var = substr($method, 3, strlen($method)-3); 
     $this->$var = $args[0]; 
    } else { 
     //throw exception 
    } 
} 

} 
相关问题