我得到了2个class Node和ChildNode,ChildNode扩展了Node。父级中有属性:
class Node {
protected $discount;
public function __construct($discount) {
$this->discount = $discount;
我在那里像整数值一样使用它,在ChildNode中我需要保存整数值数组
class ChildNode extends Node {
public function __construct(Array $discount) {
$this->discount = $discount;
这样做正常吗?
我看不出有任何问题。如果有多个类都将受益于以这种方式构建的父类,那么将来可以很容易地将另一个方法或另一个变量同时添加到所有子类中。我还检查了PHP是如何处理继承的,因为我不能100%确定这一点,也因为如果你分配给$this->doesnotexistyet="magic!";但是下面输出以下。。。
class A {
protected $d;
public function __construct() {
$this->d = "A";
}
public function getDP() {
return $this->d;
}
}
class B extends A {
public function __construct() {
$this->d = "B";
}
public function getD() {
return $this->d;
}
}
$a = new A();
echo $a->getDP() . PHP_EOL;
$b = new B();
echo $b->getD() . PHP_EOL;
echo $b->getDP() . PHP_EOL;
var_dump($a , $b);
输出。
A
B
B
object(A)#1 (1) {
["d":protected]=>
string(1) "A"
}
object(B)#2 (1) {
["d":protected]=>
string(1) "B"
}
这对我来说比任何事情都重要,但我想如果它能帮助其他遇到这种情况的人,我会添加它。