gpt4 book ai didi

php - yii2 - 有人可以解释 parent::init(); 的含义吗?陈述

转载 作者:行者123 更新时间:2023-12-04 16:01:23 24 4
gpt4 key购买 nike

网上查了一下parent::init();的意思.我所能找到的只是 init() 是初始化一些设置,这些设置希望在每次应用程序运行时出现。谁能准确解释 parent::init() 的含义,比如这两个词的含义?在此先感谢。(如果它太简单了,我很抱歉!)

最佳答案

当我们使用 parent::init() 时,我们只是在当前类的方法中调用父方法(在本例中为 init())。

关于 parent ::

例如,假设我们有一个名为 MyClass 的类。这个类有一个很棒的方法可以运行很多东西:

class MyClass
{
public function runStuffs()
{
// trigger events, configure external stuff, adding default values to properties.
}
}

现在,一段时间后,我们决定创建一个从第一个类扩展而来的新类。我们调用了 MySecondClass:

class MySecondClass extends MyClass
{

}

它已经有了 runStuffs() 方法,但是,对于第二个类,我们需要在这个方法中做更多的事情,但要保持它所拥有的。

当然,我们可以重写整个方法,只需复制并粘贴我们在 MyClass 中的内容,然后添加新内容。但这不是优雅的,甚至不是一个好的做法。如果稍后我们更改 MyClass 中的方法,您可能希望 MysecondClass 也进行更改。

因此,为了解决这个问题,我们可以在编写新内容之前调用父方法:

class MySecondClass extends MyClass
{
public function runStuffs()
{
parent::runStuffs();

// do more things!
}
}

现在 MySecondClass->runStuffs() 将始终执行其父级执行的操作,然后执行更多操作。

关于 init() 方法。

init()是 Yii2 框架中几乎所有类中使用的方法(因为大多数类在某些时候从 yii\base\Object 扩展)并且工作方式与 __constructor() 一样方法(原生于 PHP)。但是有一些不同,你可以阅读更多here .

实际上 init() 方法是在 __constructor() 内部调用的,框架鼓励我们使用 init() 而不是__construct() 只要有可能。

如果两者几乎相同,为什么要创建此方法?有一个答案 here . (看看 qiang 的回答,来自开发团队):

One of the reasons for init() is about life cycles of an object (or a component to be exact).

With an init() method, it is possible to configure an object after it is instantiated while before fully initialized. For example, an application component could be configured using app config. If you override its init() method, you will be sure that the configuration is applied and you can safely to check if everything is ready. Similar thing happens to a widget and other configurable components.

Even if init() is called within constructor rather than by another object, it has meaning. For example, in CApplication, there are preInit() and init(). They set up the life cycles of an application and may be overridden so that the customization only occurs at expected life cycles.

结论

因此,当您使用 init() 方法并调用 parent::init() 时,您只是说您想向该方法添加更多内容而不删除它已经在做什么。

关于php - yii2 - 有人可以解释 parent::init(); 的含义吗?陈述,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37559386/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com