dsds661730652211 2015-11-05 16:45
浏览 34
已采纳

从php中的子类获取数组中的常量

i have following problem. I have child class which contains only constants. I have variable constants in parent class. I need get constants as variable in parent class. I try

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

But this behaves only if I call this in child constructor. I need call this in parent construnctor. Is there any possibilites how to do this?

Thanks a lot

  • 写回答

1条回答 默认 最新

  • douchenzhan3050 2015-11-05 17:12
    关注

    Your implementation simply goes against the inheritance model. You might need to consider a refactor.

    This is what it sounds like your current setup is:

    class A {
        function __construct() {
            $this->constants = $this->getConstants()
        }
    }
    
    class B extends A {
      public function getConstants() {
          return [1, 2, 3];
      }
    }
    

    You will not be able to call getConstants from within the Class A declaration. Class A does not have such a function defined, and it also does not know (or care) whether or not it is an instance of Class B.

    It almost sounds like you have your hierarchy reversed:

    class A extends B {
        public $constants;
        function __construct() {
            $this->constants = $this->getConstants()
        }
    }
    
    class B {
      public function getConstants() {
          return [1, 2, 3];
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改