是从另一个类调用类

时间:2021-09-06 16:05:21

Suppose I have the following code:

假设我有以下代码:

class siteMS
 {
    ...
    function __CONSTRUCT()
     {
        require 'config.php';
        $this->config = new siteMSConfig;
        ...
     }
    ...
 }

From inside the siteMSConfig class can I determine weather or not it is being called from inside the siteMS class?

从siteMSConfig类内部可以确定是否从siteMS类内部调用它?

3 个解决方案

#1


Yes, but there's no "pretty" way to do it - you'll end up looking through a backtrace or something similar.

是的,但没有“漂亮”的方式去做 - 你最终会通过回溯或类似的东西来看。

It would be better to pass an (optional?) parameter to the siteMSConfig constructor like this:

最好将(可选的?)参数传递给siteMSConfig构造函数,如下所示:

class siteMSConfig
{
    public function __construct($inSiteMS = false)
    {
    }
}

or alternatively, subclass siteMSConfig:

或者,子类siteMSConfig:

class siteMSsiteMSConfig extends siteMSConfig
{
    public function __construct()
    {
        // Possibly call parent::__construct();
    }
}

#2


Technically yes, you could use debug_backtrace to figure out who your caller was.

从技术上讲,您可以使用debug_backtrace来确定调用者是谁。

Writing a class which alters its behaviour based purely on where it called from is asking for a world of pain later on though. Why not parameterise the different behaviour, or make a subclass?

写一个改变其行为的类,纯粹基于它所调用的地方,但后来却要求一个痛苦的世界。为什么不参数化不同的行为,或者做一个子类?

#3


I guess you have to pass it with variable, from what place you called it

我想你必须用变量传递它,从你调用它的位置

$this->config = new siteMSConfig ('siteMS');

#1


Yes, but there's no "pretty" way to do it - you'll end up looking through a backtrace or something similar.

是的,但没有“漂亮”的方式去做 - 你最终会通过回溯或类似的东西来看。

It would be better to pass an (optional?) parameter to the siteMSConfig constructor like this:

最好将(可选的?)参数传递给siteMSConfig构造函数,如下所示:

class siteMSConfig
{
    public function __construct($inSiteMS = false)
    {
    }
}

or alternatively, subclass siteMSConfig:

或者,子类siteMSConfig:

class siteMSsiteMSConfig extends siteMSConfig
{
    public function __construct()
    {
        // Possibly call parent::__construct();
    }
}

#2


Technically yes, you could use debug_backtrace to figure out who your caller was.

从技术上讲,您可以使用debug_backtrace来确定调用者是谁。

Writing a class which alters its behaviour based purely on where it called from is asking for a world of pain later on though. Why not parameterise the different behaviour, or make a subclass?

写一个改变其行为的类,纯粹基于它所调用的地方,但后来却要求一个痛苦的世界。为什么不参数化不同的行为,或者做一个子类?

#3


I guess you have to pass it with variable, from what place you called it

我想你必须用变量传递它,从你调用它的位置

$this->config = new siteMSConfig ('siteMS');