【发布时间】:2012-04-21 15:08:28
【问题描述】:
我正在尝试扩展一个 PHP 类而不重写整个事情。这是一个例子:
<?
$a = new foo();
print $a->xxx();
$b = new bar();
print $b->xxx();
class foo {
const something = 10;
public function xxx() {
$this->setSomething();
return $this->something;
}
private function setSomething() {
$this->something = self::something;
}
}
class bar extends foo {
public function xxx() {
$this->setSomething();
$this->something++;
return $this->something;
}
}
?>
但是,当我运行脚本时,出现以下错误:
Fatal error: Call to private method foo::setSomething() from context 'bar' in test.php on line 23
似乎 bar 没有继承私有函数 setSomething()。在不修改 foo 类的情况下如何解决这个问题?
【问题讨论】:
-
你不能把
setSomething()改成protected吗? -
如上所述,foo 类是不可修改的。我还能怎么做?
-
你使用了正确的工具来完成这项工作,也就是说,将其设为
protected。 -
我理解你的意思但是我没有权限改变原来的班级。也许我过于简化了这个例子。原始类来自仅包含在 require() 中的另一个文件。
-
在这种情况下,作者不希望它在子类中可用。或者在设计阶段没有考虑。所以这是该父类的设计规则。
标签: php class inheritance