doudu161481 2013-10-02 08:18 采纳率: 100%
浏览 37
已采纳

强制子类初始化受保护的属性

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?

  • 写回答

1条回答 默认 最新

  • du9698 2013-10-02 13:34
    关注

    I would agree on passing parameters in the constructor. Why? Well, what is a constructor anyway? It is what constructs an object. If you are making a pizza, you have to construct it using dough. All other ingredients are optional. If your pizza object is dependent on dough, pass it through the constructor, because pizza isn't pizza without it. What about ketchup? Ketchup is optional. That is why we don't construct the pizza with it. We make a setter and the user can set (add) ketchup if he/she wants it. Should we make a setter for dough? Yes, because we didn't build() our pizza yet, and it's still not too late to set some other type of dough.

    Is there another way? Probably. Using template method or something similar, but I see no point in doing so.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示
  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”