2013-10-15 33 views
1

這聽起來似乎很愚蠢,但我正面臨着PHP中靜態函數的這個問題。在PHP中使用面向對象編程仍然是新手,所以需要一些幫助。在PHP中實現靜態函數

我有一個數據庫類,它處理我的應用程序中的連接和crud操作的所有功能。我有另一個類,它擴展了DB類並使用它中的方法。

 class Database(){ 

      function db_connect(){ 
       //body 
      } 
     } 

    /*****The inheritor class*****/ 
    class Inheritor extends Database{ 
     function abcd(){ 
        $this->db_connect();   //This works good 
      } 

    } 

但現在我必須使用function abcd(){}在其他類作爲它執行相同的task.The新類是這個例如這也將擴展數據庫類:

 class newClass extends Database{ 

      function otherTask(){ 
       //Here I need to call the function abcd(); 
      } 
    } 

我試着使function abcd()靜態,但是我不能在類繼承器的函數定義中使用this。我也嘗試創建數據庫類的對象,但這是不允許的,因爲它給出了錯誤。

有人可以建議我正確的方式來實現我想要的嗎?

+3

你'newClass'需要延續'Inheritor'不'Database' – cmorrissey

+0

威爾也讓我可以訪問到'Database'方法? @ChristopherMorrissey – coderunner

+0

聽起來像'newClass'應該'擴展Inheritor',或者''function abcd'應該是'Database'的成員。這是關於將您的代碼和類層次結構進行邏輯分組的,這很難在不知道每個類的真正目的的情況下給出任何建議。 – deceze

回答

3

您可以簡單地擴展Inheritor類。這將使您可以訪問DatabaseInheritor方法。

class NewClass extends Inheritor { 
    function otherTask() { 
     //... 
     $this->abcd(); 
     //... 
    } 
} 
2

當你擴展一個類時,新的類繼承了前面的方法。 例子:

Class database{ 
Method a(){} 
Method b(){} 
Method c(){} 
} 
Class inheritor extends database{ 
//this class inherit the previous methods 
    Method d(){} 
} 
Class newCalss extends inheritor{ 
    //this class will inherit all previous methods 
    //if this class you extends the database class you will not have 
    //the methods d() 

}