2014-01-13 27 views
0

我對PHP中的OOP真的很新,所以請在這裏和我一起討論。PHP中的分組方法

有什麼辦法可以將課堂中的某些功能分組?有點像創建一個子類。

例如,我該怎麼做這樣的事情?:

className::food::fruit('lemon'); 

這可能嗎?

+1

你可以從另一個擴展你的課程。 a類擴展b ...然後b類可以訪問a:s方法。延伸鏈可以像你想的那樣深。 – makallio85

回答

2

你不能在單個類成基於這樣的類名不同的參考路徑內的直接獨立的功能。最接近的可用事情是使用命名空間(可從PHP 5.3+獲得)並在您的命名空間中創建多個類,每個類都有自己的一組函數。例如:

namespace className; 

class food { 

    static function fruit() { 

    } 

} 

會通過

className\food::fruit('lemon'); 

叫這沒有意義調用一個命名空間「的className」 - 只用來搭配你的榜樣。

如果您需要更多的組級別,名稱空間可以有很多級別的嵌套。

注意這與您的示例有根本的不同,因爲這將最終以多個類來實現按照您的示例進行函數分組,這裏我認爲您正在尋找類似的解決方案,但僅使用一個類 - 這是不可能。

注意這與顯示繼承的其他答案不同 - 因爲它們提供了不同的分組位置來定義函數,但不允許以明顯不同的方式在現有對象上引用它們或靜態地從類本身引用它們。

點擊此處瞭解詳情:http://php.net/namespaces

注 - 我認爲繼承會根據您的示例代碼,以正確的方式去 - 命名空間不聽起來像是一個非常適合給出的例子 - 但是,如果你想在你的問題中提到的「子類」,這可能更接近你正在尋找的東西。

兩者的結合可能會給出最好的結果(並且是很常見的做法)。

0

PHP支持繼承,所以你可以編寫一個水果類,然後寫一個繼承水果的子類檸檬。

0

看到這個例子使用類擴展和抽象類。

// Abstract class can regisiter functions that MUST be implemented by extending 
// classes 
abstract class Fruit { 
    public function type(); 
} 

// Lemon extends Fruit, so it must implement its own version of the type() method. 
class Lemon extends Fruit { 
    public function type() { 
     return "Lemon"; 
    } 
} 

// Grape also extends Fruit, but this will create an error because it is not 
// implementing the type() method in the abstract class Fruit 
class Grape extends Fruit { 
} 


$lemon = new Lemon(); 
echo $lemon->type(); 

// This will give you an error because the Grape class did not implement the 
// type() as the Fruit class requires it to. 
$grape = new Grape(); 
echo $grape->type(); 

PHP文檔在解釋類擴展方面做得很好。

http://www.php.net/manual/en/language.oop5.abstract.php