PHP继承:子类重写父变量/属性,用于构造函数

时间:2013-08-01 15:46:01

标签: php inheritance simpletest

我有一个(抽象)父类应该在构造期间提供功能。子类可以覆盖构造函数中使用的属性:

class Parent extends MiddlewareTest
{
    // abstract channel properties
    protected $title = NULL;
    protected $type = NULL;
    protected $resolution = NULL;

    function __construct() {
        parent::__construct();

        $this->uuid = $this->createChannel($this->title, $this->type, $this->resolution);
    }
}

class Child extends Parent
{
    // channel properties
    protected $title = 'Power';
    protected $type = 'power';
    protected $resolution = 1000;
}

问题是当未覆盖的Child::__construct()运行时($this->createChannel使用NULL参数调用)时,不会使用重写的属性。

这可能在PHP中使用,还是每次都必须使用重写子构造函数来提供所需的功能?

注意:我看到Properties shared between child and parents class in php,但这是不同的,因为子属性未在构造函数中分配,而是按照定义。

更新

事实证明我的测试用例有问题。由于MiddlewareTest基于SimpleTest单元测试用例,所以SimpleTest实际上是我没有意识到的 - 它的自动运行实例化了父类本身,它从未被用过。通过使Parent类抽象来修复。

经验教训:建立一个干净的测试用例并在哭泣之前实际运行它。

1 个答案:

答案 0 :(得分:2)

我不确定你的服务器上是怎么发生的。我必须对MiddlewareTest类做出假设,修改你的类名,并添加一些简单的调试行,但使用以下代码:

<?php
/**
* I'm not sure what you have in this class.
* Perhaps the problem lies here on your side.
* Is this constructor doing something to nullify those properties?
* Are those properties also defined in this class?
*/
abstract class MiddlewareTest {
    // I assume this properties are also defined here
    protected $title = NULL;
    protected $type = NULL;
    protected $resolution = NULL;
    protected $uuid = NULL;

    public function __construct()
    {}

    protected function createChannel($title, $type, $resolution)
    {
        echo "<pre>" . __LINE__ . ": "; var_export(array($this->title, $this->type, $this->resolution)); echo "</pre>";
        echo "<pre>" . __LINE__ . ": "; var_export(array($title, $type, $resolution)); echo "</pre>";
        return var_export(array($title, $type, $resolution), true);
    }
}

// 'parent' is a keyword, so let's just use A and B
class A extends MiddlewareTest
{
    // abstract channel properties
    protected $title = NULL;
    protected $type = NULL;
    protected $resolution = NULL;

    function __construct() {
        parent::__construct();

        echo "<pre>" . __LINE__ . ": "; var_export(array($this->title, $this->type, $this->resolution)); echo "</pre>";
        $this->uuid = $this->createChannel($this->title, $this->type, $this->resolution);
        echo "<pre>" . __LINE__ . ": "; var_export($this->uuid); echo "</pre>";
    }
}

class B extends A
{
    // channel properties
    protected $title = "Power";
    protected $type = "power";
    protected $resolution = 1000;
}

$B = new B();
?>

我得到了这些结果:

37: array (
  0 => 'Power',
  1 => 'power',
  2 => 1000,
)

20: array (
  0 => 'Power',
  1 => 'power',
  2 => 1000,
)

21: array (
  0 => 'Power',
  1 => 'power',
  2 => 1000,
)

39: 'array (
  0 => \'Power\',
  1 => \'power\',
  2 => 1000,
)'

正如您所看到的那样,值就像在实例化类中定义一样传递,就像预期的那样。

您能否提供一些有关您的MiddlewareTest课程的详细信息,这些详细信息可能会说明您可能遇到此行为的原因?

你在运行什么版本的php?