OOP~PHP,不同的函数方法?

时间:2013-03-30 15:48:09

标签: php

我一直在阅读可以在OOP样式开发区中使用的各种方法的手册。

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

^^为什么会这样?为什么不能在原始类中包含这些函数。

我的总体问题是,为什么我会使用AbstractStaticProtectedextends

1 个答案:

答案 0 :(得分: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。我从未发现需要private用PHP。)