在PHP中的子构造函数之前调用父构造函数 [英] Call parent constructor before child constructor in PHP

查看:72
本文介绍了在PHP中的子构造函数之前调用父构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有可能在孩子的__construct()之前用PHP继承调用父__construct()。

I was wondering if its possible to call the parents __construct(), before the child's __construct() with inheritance in PHP.

示例:

class Tag {
     __construct() {
         // Called first.
     }
}

class Form extends Tag {
     __construct() {
         // Called second.
     }
} 

new Form();

理想情况下,我可以在它们之间做点什么。如果这是不可能的,有没有替代方案,这将允许我这样做?

Ideally, I would be able to do something in between them. If this is not possible, is there an alternative, which would allow me to do this?

我想这样做的原因是能够加载一堆表格可以在调用__construct()时使用的标签的默认设置。

The reason I want to do this is to be able to load a bunch of default settings specific to the Tag that Form can use when __construct() is called.

编辑:抱歉忘记添加此..我不想打电话子类中的父类。这只是因为它将一些私人数据(对于父母)暴露给孩子,当你将其作为参数传递时

这就是我想要做的:

$tag = new Tag($privateInfo, $publicInfo);
$tag->extend(new Form()); // Ideal function, prob doesn't work with inheritance.

Tag.php

class Tag {
     private $privateInfo;
     public $publicInfo;
     __construct($private, $public) {
         $this->privateInfo = $private;
         $this->publicInfo = $public;
     }
} 

Form.php

class Form extends Tag {

     __construct() {
         echo $this->publicInfo;
     }
} 

有意义吗?

谢谢!
Matt Mueller

Thanks! Matt Mueller

推荐答案

只需在孩子中调用parent :: __ construct。

Just call parent::__construct in the child.

class Form extends Tag
{
    function __construct()
    {
        parent::__construct();
        // Called second.
    }
}

这篇关于在PHP中的子构造函数之前调用父构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆