php – 抽象类方法声明
|
我刚写了这样的代码: <?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();
?>
当我运行此代码时,我收到以下错误:
我理解这个错误的第一部分.我将类测试更改为抽象,错误消失了,但是我无法理解的部分. 如果要添加抽象方法,那么您还需要使类抽象化.这样,该类无法实例化 – 只有非抽象子类才可以.visibility(参见第二小节Method Visiblilty)在子类中不相同.根据您是否希望通过子类之外的代码调用方法,可以使类test中的(抽象)方法为public,或者使子类方法也受到保护. 请注意07002的第二段,其中解释了这一点:
<?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
?> (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
