我刚写了这样的代码:
<?php
class test
{
// Force Extending class to define this method
abstract protected function getValue();
abstract protected function prefixValue($prefix);
// Common method
public function printOut() {
print $this->getValue() . "\n";
}
}
class testabs extends test{
public function getValue()
{
}
public function prefixValue($f)
{
}
}
$obj = new testabs();
?>
Run Code Online (Sandbox Code Playgroud)
当我运行此代码时,我收到以下错误:
致命错误:类测试包含2种抽象方法,因此必须声明为抽象或实现其余的方法(试验::的getValue,测试:: prefixValue)在C:\ wamp64 \第12行WWW \研究\ abstract.php
我理解这个错误的第一部分.我将类测试更改为抽象,错误消失了,但or我无法理解的部分.
如果要添加抽象方法,那么您还需要创建类abstract.这样,该类无法实例化 - 只有非抽象子类才可以.
的能见度(参考第二子部分的方法Visiblilty)不是在子类中的相同.根据您是否希望通过子类之外的代码调用方法,您可以在类中创建(抽象)方法test public,或者也可以创建子类方法protected.
请注意Class Abstraction页面中的第二段,它解释了这一点:
从抽象类继承时,父类声明中标记为abstract的所有方法都必须由子类定义; 此外,必须使用相同(或限制较少)的可见性来定义这些方法.例如,如果将抽象方法定义为protected,则必须将函数实现定义为protected或public,而不是private
<?php
abstract class test{
// Force Extending class to define this method
abstract protected function getValue();
abstract protected function prefixValue($prefix);
// Common method
public function printOut() {
print $this->getValue() . "\n";
}
}
class testabs extends test{
protected function getValue()
{
}
/**
* this method can be called from other methods with this class
* or sub-classes, but not called directly by code outside of this class
**/
protected function prefixValue($f)
{
}
}
$obj = new testabs();
// this method cannot be called here because its visibility is protected
$obj->prefixValues();// Fatal Error
?>
Run Code Online (Sandbox Code Playgroud)