【问题标题】:PHP, using parent class properties as another type in child classPHP,使用父类属性作为子类中的另一种类型
【发布时间】:2014-09-18 00:33:39
【问题描述】:

我有 2 个类 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 oop polymorphism


【解决方案1】:

我认为这没有任何问题。如果您有多个类都将从这种结构的父类中受益,那么将来可以轻松地将另一个方法或另一个变量添加到所有子类中。我还检查了 PHP 如何处理继承,因为我不是 100% 确定这一点,而且如果你分配给类似 $this->doesnotexistyet = "magic!"; 的东西,php 会自动为你设置变量。但是下面的输出如下......

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"
}

这对我来说比什么都重要,但我想如果它可以帮助其他遇到此问题的人,我会添加它。

【讨论】:

    猜你喜欢
    • 2018-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-04
    • 1970-01-01
    • 1970-01-01
    • 2019-12-12
    相关资源
    最近更新 更多