I have an abstract class with methods that require values assigned by the child classes. Say:
<?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();
?>
How do I force the child classes to initialize the protected properties before usage?
$child_foo->setValue($value);
Here are some things I have considered doing:
1) Make setValue an abstract method - This could force developers to implement setValue in child classes, but they may use it improperly (DUH!)
2) A post in SO advised including the required parameters in the constructor - This may work, but just seems redundant since there's already setValue(). I plan to keep setValue() so that the same object can be reused for different inputs.
Is there any pattern for this problem which is probably common to most programs?