dtrt2368 2016-05-31 05:36
浏览 43
已采纳

我们什么时候应该在PHP的基类中使用抽象函数或普通函数?

So I have a question about the difference between "when we should declare normal function" and "when we should declare abstract function" in base class. Look at my example.

In the abstract class:

abstract class Birds {
    abstract public function fly();
}

class Swallow extends Birds {
    public function fly() {
        // This function override fly function in Birds class
        echo "Implement fly function in Swallow class";
    }
}

In the normal class:

class Birds {
    public function fly() {
        echo "Implement fly function in Birds class";
    }
}

class Swallow extends Birds {
    public function fly() {
        // This function override fly function in Birds class
        echo "Implement fly function in Swallow class";
    }
}

What you can see. The fly function in Swallow class is inherited by Birds class (in all cases). They are a same thing. So I'm embarrassed and I dont know when we should declare abstract function in base class?

Thanks for your help!

  • 写回答

2条回答 默认 最新

  • dpiw16824 2016-05-31 05:58
    关注

    Abstract functions are actually only an interface. E.g. there's no difference in your example between abstract class and if it would be an interface (that's because there's only abstract method).

    //abstract class
    abstract class Birds {
        abstract public function fly();
    }
    //interface
    interface Birds {
        public function fly();
    }
    

    That's because abstract methods have the same purpose that interface's method. When you somewhere else create a function (or method or a class or another interface etc.), and you will require any Birds instance, you will be sure you have that abstract method avaiable, although it was not implemented in Birds.

    public function sendBirdToSpace(Birds $bird) { //no matter what Bird subclass
        $bird->fly(); //you're sure this method is avaiable
    } 
    

    Also usually you will have more than one child class. When it comes to that, it's getting more clear about abstract method.

    It's actually pretty simple. Should Birds have a default behaviour implementation of flying? That's all. If every bird should can fly, but there's no default method - make it abstract.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?