因为我很懒,所以我想知道 PHP 是否有一种简写的方式来设置这样的属性...
with $person_object {
->first_name = 'John';
->last_name = 'Smith';
->email = 'spam_me@this-place.com';
}
有这样的吗?或者,是否有一种懒惰的方法来设置属性而不必一遍又一遍地键入 $person_object
?
最佳答案
您可以在您的 Person
类中实现类似于构建器模式的东西。该方法涉及在每次 setter 调用结束时返回 $this
。
$person
->set_first_name('John')
->set_last_name('Smith')
->set_email('spam_me@this-place.com');
在你的类里面......
class Person {
private $first_name;
...
public function set_first_name($first_name) {
$this->first_name = $first_name;
return $this;
}
...
}
关于php - 有没有一种设置许多对象属性的简写方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8747380/