“我只希望每个子类都可以有它的默认值”。
您希望每个类都有特定的数据。
您可以使用“静态字段”,使类本身充当变量。我不是“静态成员”的粉丝,但我认为它适用于您的“用例”。
class Foo {
private
// (1) "private" only accessed by the class itself,
// neither external code, or subclasses,
// (2) "static", specific to the class,
static $defaults = array(1, 2);
protected
// want to be accessed only by class & subclasses
$options = array();
// when using "static fields" in constructor,
// you need to override constructor
public function __construct($options){
array_push($this->options, Foo::$defaults);
}
// ops, "print" is reserved identifier
// public function print(){
public function display_options() {
print_r($this->$options);
}
public function display_defaultoptions() {
// in order to acccess "static fields",
// you use the class id, followed by double colon,
// not "$this->*"
print_r(Foo::$defaults);
}
} // class Foo
class Bar extends Foo {
private
// (1) "private" only accessed by the class itself,
// neither external code, or subclasses,
// (2) "static", specific to the class,
static $defaults = array(1, 2);
// when using "static fields" in constructor,
// you need to override constructor
public function __construct($options){
array_push($this->options, Bar::$defaults);
}
public function display_defaultoptions() {
// in order to acccess "static fields",
// you use the class id, followed by double colon
// not "$this->*"
print_r(Bar::$defaults);
}
} // class Bar
$bar = new Bar();
$bar->print();
干杯