【问题标题】:PHP: change attribute from inherited classPHP:从继承的类更改属性
【发布时间】:2011-02-04 08:56:15
【问题描述】:

也许你们中的一些人使用 jpgraph 来生成一些图表。我想从 jpgraph-class ( ErrorPlot ) 更改私有属性 ($errwidth)。在大多数情况下,jpgraph 提供了一个设置所有必要属性的功能。但在这种情况下不是。

这是我的尝试:

class ErrorPlot extends Plot { 
  // Original class
  private $errwidth=2; 
  ...
}

class SpecialErrorPlot extends ErrorPlot { 
  // "Extension" to modify the attribute
  function SetErrWidth( $w ){
    $this->errwidth = $w;
  }
}

$chart_obj = new SpecialErrorPlot( array(1,2,3,4,5,6) );
$chart_obj->SetErrWidth(10);


SpecialErrorPlot Object (
  [errwidth:private] => 2
  ...
  [errwidth] => 10
)

结果:2 个属性!获得这两个属性已经够糟糕了,但我不明白为什么!?!?我希望你能帮助我!

斯蒂芬

【问题讨论】:

    标签: php class inheritance private


    【解决方案1】:

    你想要保护而不是私有。

    受保护的函数和变量可以由子类修改,而私有函数和变量只能由该类修改。

    【讨论】:

      【解决方案2】:

      你应该看看反射 - setAccessible()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-12-16
        • 2015-05-03
        • 2023-03-09
        • 2011-04-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-13
        相关资源
        最近更新 更多