2012-08-02 129 views
1

我有我的PHP項目中的每個MySQL表的單獨的類。類會是這樣的:擴展PHP類

class students { 

    public static function find_all() { 
     return self::sql_finder("SELECT * FROM ".get_class()); 
    } 

} 

我用的是同一類的幾乎所有我在我的項目表中,除了我更改類名作爲表名。現在你可以看到我在類中使用的函數中使用了「get_class()」,所以SQL從類名中獲取表名。

因爲我有我的所有類使用類太多的功能,我打算與子類這樣的擴展類:

class class_with_all_the_common_functions { 
public static function find_all() { 
     return self::sql_finder("SELECT * FROM ".get_class()); 
    } 
} 

class student extends class_with_all_the_common_functions { 
// some table specific functions 
} 

現在,當我使用student::find_all()它顯示了一個錯誤:

Database query failed: Table 'dr.class_with_all_the_common_functions 
doesn't exist 

我想有一點清楚了,我想find_all()作爲其在類學生執行執行。這是通過後期靜態綁定可以實現的嗎?

+0

您是否嘗試過遲的靜態綁定? static :: sql_finder()而不是self :: sql_finder()? – Oussama 2012-08-02 14:07:15

+0

嗨Naveen。我可不可以要求你嘗試大寫'I'並在可能的情況下將代碼塊/內聯格式化?使其儘可能可讀可以幫助每個人,包括第一語言不是英語的人。謝謝! – halfer 2012-08-02 14:13:23

+0

嗨halfer,我是新的,事實上這是我的第一個問題,以後生病考慮你的話,謝謝 – 2012-08-03 05:26:02

回答

3

兩件事情,你會發現有用的與此相關的:

  • get_called_class()代替get_class()
  • static::foo()而不是self::foo()
+0

謝謝你,馬修工作得很好 – 2012-08-03 05:16:41

0

您可以使用get_class(parent)或使私有字段的表名和重載它,只有當它nessessary:

class A { 
    private $table = 'A'; 
} 

class B extends A { 
    public function getTable() { 
     return $this->table; //will return 'A' 
    } 
} 
+0

雖然我確實認爲非靜態解決方案通常更可取,但並沒有真正回答這個問題。 – Matthew 2012-08-02 14:10:26