PHP中的baseclass什么时候应该使用抽象函数还是普通函数?

When do we should use abstract function or normal function in base class in PHP?

所以我有一个关于 "when we should declare normal function""when we should declare abstract function" 之间的区别的问题 [=34] =].看我的例子。

摘要中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";
    }
}

正常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";
    }
}

你能看到什么。 Swallow class 中的 fly 函数被 Birds class 继承(在所有情况下)。它们是同一回事。所以我很尴尬,我不知道什么时候我们应该在基础中声明抽象函数 class?

感谢您的帮助!

摘自PHP OOP Class Abstraction:

When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same (or a less restricted) visibility. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.

这实质上是说您的Swallowclass继承(fly() 方法,如果它根据其 abstract 定义扩展 Bird class。

利用 abstract 方法的一般经验法则是当您希望 class 之间的常态时。

以下面为例:

Class Car {

    abstract public function make();
    abstract public function model();
}

这是我们的"base"class。从 this has 的任何内容指定 make() & model() 方法。

Class Tesla extends Car {

    public function make() {}

    public function mmodel() {}
}

如您所见,我们的 Tesla class 中包含所需的方法。如果您不包含这些方法,则会抛出 PHP 个错误。


备注

如果你正在探索 "container" 的这种选择,比如开发,那么我建议你也好好看看 PHP OOP Object Interfaces,非常值得!

抽象函数实际上只是一个接口。例如。 abstract class 和 if it would be an interface 之间的示例没有区别(那是因为只有抽象方法)。

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

那是因为抽象方法与接口的方法具有相同的目的。当你在其他地方创建一个函数(或方法或 class 或另一个接口等)时,你将需要任何 Birds 实例,你将确保你有可用的抽象方法,尽管它是未在 Birds.

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

通常你会有多个 child class。说到这里,抽象方法就越来越清楚了。

其实很简单。 Birds 是否应该有一个 flying 的默认行为实现?就这样。如果每只鸟都应该飞翔,但没有默认方法 - 将其抽象化。