2011-09-22 28 views
1

我有一個abstract類和兒童:PHP與未知參數擴展

abstract class Cubique_Helper_Abstract { 
    abstract public function execute(); 
} 

class Cubique_Helper_Doctype extends Cubique_Helper_Abstract{ 
    public function execute($type) {} 
} 

正如你所看到的,方法​​是常見的。但是在所有的類別中參數的數量可能不同。我怎樣才能保持這種擴展方法的不同論點?

這是我目前的錯誤:

Declaration of Cubique_Helper_Doctype::execute() must be compatible 
with that of Cubique_Helper_Abstract::execute() 

謝謝你,我的進步。

+0

您可以使用'func_get_args'獲取參數,而不是在簽名中定義它們。或者在抽象類中,你可以定義方法來接受一個值,它是一個(關聯)數組。在兒童課程中,您只需訪問您需要的密鑰。 –

+0

@stereofrog:我絕對贊同+1。爲了我的學習目的,你會在下面評論我的答案嗎?歡呼聲 – chelmertz

回答

2
  • 你可以從抽象刪除​​,但你可能不希望這樣做。

  • 你也可以給它一個數據對象作爲參數,就像這樣:

    class MyOptions { 
        public function getType(){} 
        public function getStuff(){} 
    } 
    
    abstract class Cubique_Helper_Abstract { 
        abstract public function execute(MyOptions $options); 
    } 
    
    class Cubique_Helper_Doctype extends Cubique_Helper_Abstract{ 
        public function execute(MyOptions $options) { 
        $type = $options->getType(); 
        } 
    } 
    
  • 或者,你可以把它取決於值在構造函數和離開了論據:

    abstract class Cubique_Helper_Abstract { 
        abstract public function execute(); 
    } 
    
    class Cubique_Helper_Doctype extends Cubique_Helper_Abstract{ 
        public function __construct($type) { 
        // since __construct() is not in abstract, it can be different 
        // from every child class, which let's you handle dependencies 
        $this->type = $type; 
        } 
        public function execute() { 
        // you have $this->type here 
        } 
    } 
    

最後的選擇是我的最愛。這樣,你真的確定你有依賴關係,什麼時候到​​你不必給它任何參數。


,因爲你失去跟蹤依賴的我會不使用func_get_args()。例如:

class Cubique_Helper_Doctype extends Cubique_Helper_Abstract { 
    public function execute() { 
    $args = func_get_args(); 
    $type = $args[0]; 
    $title = $args[1]; 
    $content = $args[2]; 
    // do something, for example 
    echo $type; // will always echo "" if you miss arguments, but you really want a fatal error 
    } 
} 

$d = new Cubique_Helper_Doctype(); 
$d->execute(); 
// this is a valid call in php, but it ruins your application. 
// you **want** it to fail so that you know what's wrong (missing dependencies) 
+0

@stereofrog乾杯。我同意你的「公開」,但「抽象」對於抽象類型的暗示/訂立合同很有用。我看到你對這個話題的其他答案,我認爲你提出的案例在那裏(例如'if($ _ GET ['bla'] =='bla')$ class ='BlaClass';'對某些人來說是合理的,但是如果你測試事先了解你的課程,你會知道他們是否工作,你仍然可以從摘要中受益。更糟的是,更難測試,如果你問我,就不用編譯就暗示情況:) – chelmertz

1

您可以使用func_get_arg,以便子類的方法簽名是相同的。

1

當參數的數目是不同的,您會收到錯誤:

Fatal error: Declaration of Cubique_Helper_Doctype::execute() must be compatible with that of Cubique_Helper_Abstract::execute() in C:\wamp\www\tests\41.php on line 16 

所以你唯一的選擇就是讓arguement數組和它傳遞的實際參數或使execute聲明沒有參數,並用func_get_argsfunc_get_argfunc_num_args

3

將參數發送出去,您可以使用無限制的參數來創建方法或函數。

function test(){ 
$num = func_num_args(); 
for ($i = 0;$i < $num;$i++) 
{ 
    $arg[$i] = func_get_arg($i); 
} 
    // process on arguments 
}