我有兩個幾乎相同的方法,都稱爲myMethod(),但myChild2 :: myMethod()有一個額外的代碼行,它使用本地變量。我寧願不在兩個子類中重複代碼。我想我可以將myMethod移動到myParent,然後添加一個if語句來檢測哪個子類正在調用該方法,但我猜測這是不對的。什麼是最乾淨的方式來做到這一點?謝謝兩個類使用的修改方法
class myParent
{
//code...
}
class myChild1 extends myParent
{
public function myMethod()
{
// A bunch of code common to both myChild1::myMethod() and myChild2::myMethod() goes here
// A bunch more code common to both myChild1::myMethod() and myChild2::myMethod() goes here
}
}
class myChild2 extends myParent
{
public function myMethod()
{
// A bunch of code common to both myChild1::myMethod() and myChild2::myMethod() goes here
someOtherLineOfCode($someLocalVariable); // A single unique line of code goes here which uses a local variable
// A bunch more code common to both myChild1::myMethod() and myChild2::myMethod() goes here
}
}
謝謝。看起來沒有完全清潔的解決方案。作爲第四個選項,請參閱schlimpf的建議。 – user1032531 2013-04-23 16:36:25
方法1不能用於我的應用程序,因爲它不能獨立於myMethod()的其餘部分執行。你會推薦通過一個標誌或檢測類名嗎? – user1032531 2013-04-23 16:40:33
檢測調用類名將需要更少的代碼行,因爲您不必重寫'myMethod()',而是使父項依賴於存在特定名稱的子項。如果這是我的代碼,我不得不在兩者之間做出選擇,我會選擇標誌選項。 – 2013-04-23 16:44:32