PHP/OOP method overriding the DRY way

前端 未结 4 501
梦如初夏
梦如初夏 2021-01-14 10:15

I\'m curious if there is a \"better\" design for the following behavior:



        
4条回答
  •  一个人的身影
    2021-01-14 10:38

    I dont think this is better, but this is one possible way.

    class abstract Foo {
        public function foo() {
            // Foo-specific foo stuff.
            $this->_foo();
        }
    
        // Might be abstract, might be an empty implementation
        protected abstract function _foo();
    }
    
    class Bar extends Foo {
        protected function _foo() {
            // Bar-specific foo stuff.
        }
    }
    

    Personally, I prefer the way you have it because I think it is more readable. It also means the child does not have to have its own implementation of foo(). Seems more OOP. However, if you require each child class to have its own added implementation of foo() this may do the trick for you.

提交回复
热议问题