PHP继承:子类重写父变量/属性,以便在构造函数中使用


PHP inheritance: child class overriding parent variable/property for use in constructor

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

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()运行时(使用NULL参数调用$this->createChannel),不使用重写的属性。

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

注意:我在php中看到了子类和父类之间共享的Properties,但这是不同的,因为子属性不是在构造函数中分配的,而是根据定义分配的。

更新

原来我的测试用例有问题。由于MiddlewareTest是基于SimpleTest单元测试用例的,所以SimpleTest实际上——我没有意识到——通过它的自动运行实例化了Parent类本身,这是从未打算过的。通过将Parent类设为抽象类修复了此问题。

经验教训:建立一个干净的测试用例,并在请求帮助之前实际运行它。

我不确定您的服务器上是如何发生这种情况的。我不得不对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版本是什么?