在 php 中分析摘要 class

Analyze abstract class in php

我对抽象有点困惑class!我已经阅读了更多写在 Whosebug 和另一个网站上的 post 但我不明白!所以我又看了一遍我的书,但我也没看懂。所以请一步步分析下面的代码:

提前致谢

<?php
abstract class AbstractClass
{
 abstract protected function getValue();
 public function printOut() {
 print $this->getValue();
 }
}
class ConcreteClass1 extends AbstractClass
{
 protected function getValue() {
 return "ConcreteClass1";
 }
}
class ConcreteClass2 extends AbstractClass
{
 protected function getValue() {
 return "ConcreteClass2";
 }
}
$class1 = new ConcreteClass1;
$class1->printOut();

$class2 = new ConcreteClass2;
$class2->printOut();
?>

你的代码是正确的。 Abstract class 的意思是,当你不能对它进行实例化时。你不能这样做:

$abstract = new AbstractClass();

根据定义

'An abstract class is a class that is declared abstract —it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed. An abstract method is a method that is declared without an implementation'.

如果定义了一个抽象 class,您应该用另一个扩展 class。 如果在抽象 class 中有抽象方法,您应该将它们写在 child class 中,以便实例化 child.

与代码有关,这就是为什么在实例化ConcreteClass时,getValue函数是'overwritten'到pattern,而调用printOut方法是从父亲本身,因为它已经被写入并且没有被 child 覆盖。 (另请参阅该方法不是抽象的,这就是为什么您也可以从父亲那里使用它的原因 class)