我有一个抽象类,其方法需要子类分配的值。说:
<?php
abstract class Foo {
protected $value;
/* ..... other required properties here */
public function setValue($value) {
$this->value=$value;
}
public function getProcessedValue() {
// some processing here using $this->value;
return $processed_value;
}
/* ..... other public methods here using protected properties as inputs */
} end of class Foo
class ChildFoo extends Foo {
/* addtional code here */
} // end of class ChildFoo
// in main code
$child_foo=new ChildFoo();
$child_foo->setValue($value); /* how do you force this????? */
echo $child_foo->getProcessedValue();
?>
如何强制子类在使用前初始化受保护的属性?
$child_foo->setValue($value);
以下是我考虑过的一些事情:
1) 使 setValue 成为抽象方法 - 这可能会迫使开发人员在子类中实现 setValue,但他们可能会不正确地使用它(DUH!)
2) 建议在 SO 中的帖子在构造函数中包含所需的参数 - 这可能有效,但似乎是多余的,因为已经存在 setValue()。我计划保留 setValue() 以便可以将同一对象重用于不同的输入。
对于大多数程序来说,这个问题是否有任何常见的模式?