2013-03-30 42 views
-2

我一直在閱讀可用於OOP Style開發區的各種不同方法的手冊。OOP〜PHP,不同的函數方法?

class Class{ 
    private function SortArrayByNoExample(){ 
      $ExampleArray = array ('Item_1', 'Item_3','Item_6','Item_5','Item_4','Item_2'); 
      Echo "Original Array: <br>"; 
      print_r($ExampleArray); 
      Echo "<br><br><br>"; 
      echo "Sorted Array"; 
      natsort($ExampleArray); 

      print_r($ExampleArray); 
     } 

     public function NaturalSort ($Arg1){ 
      if (!is_array($Arg1)){ 
       $this->SortArrayByNoExample(); 
      }else{ 
       natsort($Arg1); 
       return $Arg1; 
      } 
} 

我有這個當前的情況,以此爲例。

我明白公共功能都可以通過訪問:

$Foo = new Class(); 
$Foo->PublicFunctionName(); 

及私人功能只能在類的內部訪問。

public function NaturalSort ($Arg1){ 
     if (!is_array($Arg1)){ 
      $this->SortArrayByNoExample(); 
     } 

如果這些功能完全靠自己,爲什麼是他們這樣的方法爲:

Abstractstaticprotected

然後是擴展名,如:

class AnotherClass extends Class {} 

^^爲什麼要這樣?爲什麼你不能在原來的類中包含函數。

我的整體問題是,爲什麼我會用Abstract,Static,Protectedextends

+1

閱讀_On_OO編程入門...這個問題,因爲它是廣泛的方式。 – Wrikken

回答

5

一旦你有更多的經驗,你可以很容易地理解爲什麼這些東西存在。你甚至不需要更多的經驗。

例如需要extends(子類),因此所有的其它概念是很明顯的,一旦你考慮這個人爲例子:

abstract class Animal { 
    // there are no "animal objects", only specific kinds of animals 
    // so this class is abstract 
    function eat(){} // animals all eat the same way 
    // different animals move differently, so we can't implement "move" 
    // however all animals move, so all subclasses must have a "move" method 
    abstract function move() 
    // (I'm straining things a bit here...) 
    // No one can order an animal to sleep 
    // An animal must sleep on its own 
    protected function sleep(){} 
    // note if this function were *private*, then the only the 
    // Animal class code can call "sleep()", *not* any subclasses 
    // Since a Dog and a Cat sleep at different times, we want them 
    // to be able to decide when to call sleep(), too. 
} 

abstract class FourLeggedAnimal { 
    // all four-legged animals move the same way 
    // but "four-legged-animal" is still abstract 
    function move() {} 
} 


class Dog extends FourLeggedAnimal { 
    // only dogs bark 
    function bark(){} 
} 

class Cat extends FourLeggedAnimal { 
    // only cats meow 
    function meow(){} 
} 

(順便說一句,你應該默認爲protected,而不是private,當您需要一個「不 - public」的方法。我從來沒有發現在PHP中需要private。)

+0

這是一個非常豐富的答案。如果我可以獎勵超過+1和接受。我真的會。謝謝 – user2146021

+0

@ user2146021爲你做到了。很好的答案 – thaJeztah