从 child class in php 获取数组中的常量

Get constants in array from child class in php

我有以下问题。我有 child class 只包含常量。我在 parent class 中有变量常量。我需要在 parent class 中获取常量作为变量。 我试试

$onClass = new ReflectionClass(__CLASS__);
$this->constants = $onClass->getConstants();

但这只有在我在 child 构造函数中调用它时才会起作用。我需要在 parent 构造函数中调用它。有没有可能如何做到这一点?

非常感谢

您的实现完全违背了继承模型。您可能需要考虑重构。

这听起来像是您当前的设置:

class A {
    function __construct() {
        $this->constants = $this->getConstants()
    }
}

class B extends A {
  public function getConstants() {
      return [1, 2, 3];
  }
}

您将无法从 Class A 声明中调用 getConstants。 Class A 没有定义这样的函数,它也不知道(或关心)它是否是 Class B.

的实例

听起来你的层次结构几乎颠倒了:

class A extends B {
    public $constants;
    function __construct() {
        $this->constants = $this->getConstants()
    }
}

class B {
  public function getConstants() {
      return [1, 2, 3];
  }
}