如何为需要在父级工作时运行的子级编写构造函数?

发布于 2024-12-11 02:18:37 字数 712 浏览 0 评论 0原文

我有一个家长班对所有活动进行日志记录工作。 现在我想使用子类向某些活动添加附加数据。这意味着我需要父级关于活动的变量,并且我需要在调用父级时运行子级。

这是父级的构造函数:

function CD_Log( $id = false ) {
    $this->__construct( $id );
}

function __construct( $id = false ) {

    if ( !empty( $id ) ) {
        $this->id = $id;
        $this->populate();
    }
}

这就是我认为子构造函数的样子:

function __construct( $args = array() ) {

    parent::__construct($child_id);

    $defaults = array(
    'child_id'    => 0, //the child has its own id
    'child_data'  => 0,  //extra data
    'parent_data' => $this->data // inheritage from parent
    );
}

在调用子级的函数中,我将提供默认的数据数组。孩子将在与父母被呼叫的地方相同的地方被呼叫。这段代码有效吗?

I have a parent class doing logging job on all activities.
Now I want to use a child class to add additional data to some of the activities. That means I need parent's vars about the activities, and I need to run the child when the parent is called.

This is the parent's constructor:

function CD_Log( $id = false ) {
    $this->__construct( $id );
}

function __construct( $id = false ) {

    if ( !empty( $id ) ) {
        $this->id = $id;
        $this->populate();
    }
}

This is how I think the child constructor would be:

function __construct( $args = array() ) {

    parent::__construct($child_id);

    $defaults = array(
    'child_id'    => 0, //the child has its own id
    'child_data'  => 0,  //extra data
    'parent_data' => $this->data // inheritage from parent
    );
}

In the functions that call the child, I will provide the default data array. The child will be called at the same place as parent being called. Does this code work?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迷鸟归林 2024-12-18 02:18:37

我已经读过这个问题好几遍了,发现它非常令人困惑。我真的很想帮助您,但我认为如果您更清楚地说明您想要什么以及系统应该做什么,事情会更容易。

为什么运行子类的时候还要运行父类呢?您可以尝试将信息委托给子类吗?另外,为什么要通过另一个方法调用构造函数,因为它无论如何都会在 CD_Log 方法之前初始化?

I've read the question several times and find it incredibly confusing. I would really like to help you out but think it would be easier if you clarified more on exactly what you want and what the system is supposed to do.

Why do you have to run the parent class when running the child class? Could you try and delegate the information into the child class? Also, why are you calling the constructor through another method when it will be initialized before the CD_Log method anyway?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文