2011-09-08 29 views
-4

我有一種感覺,我想做的事是不可能的,因爲我找不到任何東西。我有幾個課程是從另一個課程延伸的。在正在擴展的類中,我必須根據哪個類調用它來調用一些唯一的代碼。調用一個子類的函數

這是一個深入的項目的東西,所以我創建了一個測試用例應該解釋什麼,我試圖做的:

class parent { 
    function traverseTable($table) { 
     foreach($table->getElementsByTagName('tr') { 
      $rowCnt++; 
      $this->uniqueSearch($rowCnt); 
     } 
    } 
} 

class child1 extends parent { 
    function search($input) { 
     //parse input, get $table 
     $this->traverseTable($table); 
    } 

    function uniqueSearch($rowCnt) { 
     echo 'child1'; 
     //Do different things 
    } 
} 

class child2 extends parent { 
    function search($input) { 
     //parse input, get $table 
     $this->traverseTable($table); 
    } 

    function uniqueSearch($rowCnt) { 
     echo 'child2'; 
     //Do different things 
    } 
} 

基本上,我希望能夠調用uniqueSearch()函數從Class Parent的循環中進行;但上面的語法似乎不起作用。任何人有任何想法? uniqueSearch函數的實際大小在此處爲20-100行不等,但可能會變大。

+2

爲什麼每行實際代碼之間有空行? –

+2

你可以定義「似乎不工作」? –

回答

2

所以,你想要多態地調用uniqueSearch

  1. Your first problem無關這一點,並且是parent是一個保留字:

    Fatal error: Cannot use 'parent' as class name as it is reserved on line 2

    解決這個問題。

  2. Your next problem是一個簡單的語法錯誤:

    Parse error: syntax error, unexpected '{' on line 4

    解決這個問題。

  3. 然後,you have the issue您的測試用例中沒有$table,也沒有getElementsByTagName。另外foreach ($table->getElementsByTagName('tr'))是無效的PHP。

    修復此問題。

  4. Your testcase doesn't call any functions

    修復此問題。

結果:

<?php 
class base { 
    function traverseTable($table) { 
     foreach ($table as $element) { 
      $rowCnt++; 
      $this->uniqueSearch($rowCnt); 
     } 
    } 
} 

class child1 extends base { 
    function search($input) { 
     //parse input, get $table 
     // dummy for now: 
     $table = Array(0,1,2,3); 
     $this->traverseTable($table); 
    } 

    function uniqueSearch($rowCnt) { 
     echo 'child1'; 
     //Do different things 
    } 
} 

class child2 extends base { 
    function search($input) { 
     //parse input, get $table 
     // dummy for now: 
     $table = Array(0,1,2,3); 
     $this->traverseTable($table); 
    } 

    function uniqueSearch($rowCnt) { 
     echo 'child2'; 
     //Do different things 
    } 
} 

$c1 = new child1; 
$c2 = new child2; 

$c1->search(""); 
$c2->search(""); 
?> 

而且now it works just fine

child1child1child1child1child2child2child2child2

這個問題無關,與任何多態性,事實證明;只是愚蠢的語法錯誤。

感謝您的參與。

1

在父類中聲明uniqueSearch()作爲抽象方法(這意味着該類也必須聲明爲抽象類)。這意味着每個孩子必須執行uniqueSearch()方法本身,所以它肯定存在。

abstract class parent { 
    function traverseTable($table) { 
     foreach($table->getElementsByTagName('tr') { 
      $rowCnt++; 
      $this->uniqueSearch($rowCnt); 
     } 
    } 

    abstract function uniqueSearch($rowCnt); 
}