dtd58256 2013-07-24 06:43
浏览 76
已采纳

如何在PHP中使用其原始参数调用父类构造函数

I have this code:

class A {
  var $arr = array();

  function __construct($para) {
    echo 'Not called';
  }
}

class B extends A {
  function __construct() {
    $arr[] = 'new Item';
  }
}

And as B has its own constructor construct($para) of A never gets called.

Now I could call parent::__construct($para) but then class B would need to be aware of the parameters class A needs.

I would prefer this:

class A {
  var $arr = array();

  function __construct($para) {
    echo 'Not called';
  }
}

class B extends A {
  function __construct() {
    parent::__construct(); // With the parameters class B was created.

    // Additional actions that do not need direct access to the parameters
    $arr[] = 'new Item';
  }
}

Would something like that work?

I don't like the fact, that all classes that extend class A would need to define a new constructor, once class A changes its parameters, where all I want them to do is call the constructor of class A like when class B does not overwrite it with an own __construct() method.

  • 写回答

2条回答 默认 最新

  • dongxun6690 2013-07-24 06:50
    关注

    One solution would be to not override the parent constructor in the first place. Instead, define a separate (initially-empty) init() method that the parent constructor calls automatically. That method could then be overwritten in the child in order to perform the extra processing.

    class A {
        public function __construct($para) {
            // parent processing using $para values
    
            // ..and then run any extra child initialization
            $this->init();
        }
        protected function init() {
        }
    }
    
    class B extends A {
        protected function init() {
            // Additional actions that do not need direct access to the parameters
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 spring后端vue前端
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题