免责声明:我有点像菜鸟,只做了一年以下的PHP,并且做OO PHP不到那么。
我正在编写几个都具有相同功能的类。这是我的样板代码:
class ClassName {
// required constructor arguments
private $arg1;
// optional arguments in an array. $options array specifies their names
// and required types. '' means any type.
private $options = array('option1'=>'type', 'option2'=>'');
private $option1 = 'default_value';
private $option2 = 'default_value';
/* getters and setters would go here if I wanted them */
// this would probably change after debugging
public function __toString() {
return print_r(get_object_vars($this), true);
}
public function __construct($arg1, array $options = array()) {
// set all required args
$this->arg1 = $arg1;
// cycle through $options array, check they are allowed,
// and check their type
foreach ($options as $option => $value) {
$type = $this->options[$option]; // no value = any type is OK
if (array_key_exists($option, $this->options)
&& (gettype($value) === $type || !$type)) {
$this->$option = $value;
}
}
}
// methods go here
}
我始终如一地使用这种格式:必需的参数,然后是数组中的可选参数,使用foreach循环分配所有可选变量,指定选项及其类型(我关心的主要区别是数组与非-array)作为私人变量。
检查和分配每个可选参数的foreach循环不会改变。我可以复制并粘贴它来创建新类,但我也认为做这样的事情可能会更好,以避免重复的代码:
abstract class ParentClass {
public function __toString() {
return print_r(get_object_vars($this), true);
}
protected function setOptions($options) {
foreach ($options as $option => $value) {
$type = $this->options[$option]; // no value = any type is OK
if (array_key_exists($option, $this->options)
&& (gettype($value) === $type || !$type)) {
$this->$option = $value;
}
}
}
}
class ChildClass extends ParentClass{
private $arg1;
private $arg2;
private $options = array('option1'=>'string', 'option2'=>'array');
private $option1 = 'default_value';
private $option2 = array('foo', 'bar');
public function __construct($arg1, $arg2, $options = array()) {
$this->arg1 = $arg1;
$this->arg2 = $arg2;
parent::setOptions($options);
}
}
我还没有完成继承。这是一个很好用的吗?
谢谢!
答案 0 :(得分:2)
这将很好地利用继承,并且始终最佳做法是减少重复代码。当需求发生变化或出现错误时,DRY代码在将来修改时不那么麻烦。
编辑:顺便说一下,您还可以将所有构造逻辑放在父类的构造函数中,然后在子类中重写它,并在完成类特定逻辑时调用父构造函数。例如:
abstract class ParentClass {
public function __construct($options) {
foreach ($options as $option => $value) {
$type = $this->options[$option]; // no value = any type is OK
if (array_key_exists($option, $this->options)
&& (gettype($value) === $type || !$type)) {
$this->$option = $value;
}
}
}
public function __toString() {
return print_r(get_object_vars($this), true);
}
}
class ChildClass extends ParentClass{
private $arg1;
private $arg2;
private $options = array('option1'=>'string', 'option2'=>'array');
private $option1 = 'default_value';
private $option2 = array('foo', 'bar');
public function __construct($arg1, $arg2, $options = array()) {
$this->arg1 = $arg1;
$this->arg2 = $arg2;
parent::__construct($options);
}
}