什麼是實現這種行爲的最佳模式?Php,靜態方法和繼承..在尋找一個有效的模式
我有很多方法,比如method_1 .. method_N,可以通過一個參數進行全部參數化,比如$ k。我想有他們的一類爲靜態方法裏面,所以我當然可以寫這樣我ComputationClass:
class Computation {
static function method1($k, $otherParams) { ... }
static function method2($k, $otherParams) { ... }
static function method3($k, $otherParams) { ... }
}
現在,由於$ k屬於值的特定範圍,比如說{「狗」, 'cat','mouse'},我想創建Computation的許多子類,每個可能的值都有一個。
class Computation_Dog extends Computation {
static function method1($otherParams) { parent::method1('dog', $otherParams); }
static function method2($otherParams) { parent::method2('dog', $otherParams); }
static function method3($otherParams) { parent::method3('dog', $otherParams); }
}
class Computation_Cat extends Computation { .. }
class Computation_Mouse extends Computation { .. }
但是,這是很醜陋,讓我放棄繼承的優點:發生了什麼,如果我加入到計算的方法?有編輯所有的子類.. 後來我巧妙地切換到這一點:
abstract class Computation {
abstract static function getK();
static function method1($otherParams) { ... self::getK() .. }
static function method2($otherParams) { ... self::getK() .. }
static function method3($otherParams) { ... self::getK() .. }
}
class Computation_Dog extends Computation {
static function getK() { return 'dog'; }
}
不錯的嘗試,但它不工作,因爲似乎靜態方法不記得繼承堆棧,並自:: getK ()會調用Computation :: getK()而不是Computation_Dog :: getK()。
呃..希望能夠清楚一點..你會如何設計這種行爲? PS:我真的需要它們爲靜態方法
感謝
謝謝你的回答。是的,你說的是真的..但是,正如我指定的,我需要靜態方法..是的,Calculating_Dog類只是一個愚蠢的類包含包裝..但這正是我想要的 – user831634
我添加了一個可能的解決方案__callStatic魔術方法。它允許您將所有靜態函數調用重定向到類中不存在的函數。這樣,您不必將所有函數聲明覆制到所有包裝類。 – GolezTrol
再次感謝您,使用__callStatic是一個好方法。 – user831634