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

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

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->使用NULL参数调用createChannel),不会使用重写的属性.

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

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

更新

事实证明我的测试用例是错误的.由于MiddlewareTest基于SimpleTest单元测试用例,所以SimpleTest实际上是我没有意识到的 – 它的自动运行实例化了父类本身,它从未被用过.通过使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?

点赞