du0173
2017-11-24 10:44
浏览 202
已采纳

我们可以在php中创建没有抽象方法的抽象类吗? [关闭]

I want to know whether we can create an abstract class without abstract method in php or not.

If yes, then how the class is eligible to be called as 'Abstract Class' as it's not containing any abstract method? Further, is it a standard/supporting code practice?

If no, what is the reason behind it?

Can the abstract class only contain abstract methods, no more normal methods?

Note : I want the answer with some working suitable code example. The answer should be specific to PHP language only.

图片转代码服务由CSDN问答提供 功能建议

我想知道我们是否可以在php中创建一个没有抽象方法的抽象类。

如果是,那么该类如何被称为“抽象类”,因为它不包含任何抽象方法? 此外,它是标准/支持代码实践吗?

如果不是,背后的原因是什么?

抽象类是否只包含抽象方法,不再需要常规方法?

注意:我希望答案中包含一些合适的代码 例。 答案应仅针对PHP语言。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douzhi0107 2017-11-24 10:50
    已采纳

    An abstract class is a class that cannot be instantiated and must be extended by child classes. Any abstract methods in an abstract class must be implemented by an extending child class (or it must also be abstract). It's possible to have an abstract class without abstract methods to be implemented; but that's not particularly useful.

    The point of an abstract class is that you can define the interface in advance, but leave the implementation up to others. You can then work with that abstract interface and be sure it'll work as intended, without knowing in advance what the concrete implementation will be:

    abstract class Foo {
        abstract public function bar();
    }
    
    function baz(Foo $foo) {
        echo $foo->bar();
    }
    

    baz can depend on what $foo will look like exactly, without having any idea how it's implemented exactly.

    Having an abstract class without any abstract methods allows you to type hint Foo, but then you still don't know anything about what $foo will have in terms of methods or properties, so it's rather pointless.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题