-2

I have been reading over the manuals of a verity of different methods that can be used in a OOP Style development zone.

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;
            }
}

I have this current scenario, take this as an example.

I understand public functions can be accessed by:

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

and Private function can only be accessed from within the class.

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

If these function perfectly on their own, why is their such methods as:

Abstract, static, protected.

Then there is extensions such as:

class AnotherClass extends Class {}

^^ Why have this? Why can't you include the functions inside your original class.

My Overall question, is why would I use Abstract, Static, Protected, and extends?

4

1 回答 1

5

You can easily understand why these things exist once you have more experience. You don't even need very much more experience.

For example the need for extends (subclassing) and thus all your other concepts is quite obvious once you consider this artificial example:

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(){}
}

(BTW, you should default to protected rather than private when you need a "not-public" method. I've never found a need for private in PHP.)

于 2013-03-30T16:06:32.353 回答