我们可以在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.
我想知道我们是否可以在php中创建一个没有抽象方法的抽象类。 p>
如果是,那么该类如何被称为“抽象类”,因为它不包含任何抽象方法? 此外,它是标准/支持代码实践吗? p>
如果不是,背后的原因是什么? p>
抽象类是否只包含抽象方法,不再需要常规方法? p>
注意:我希望答案中包含一些合适的代码 例。 答案应仅针对PHP语言。 strong> p> div>
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.