tags:

views:

118

answers:

3

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?

A: 

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

$this->config = new siteMSConfig ('siteMS');
Deniss Kozlovs
+2  A: 

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:

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

or alternatively, subclass siteMSConfig:

class siteMSsiteMSConfig extends siteMSConfig
{
    public function __construct()
    {
        // Possibly call parent::__construct();
    }
}
Greg
Is reflection on the call stack possible in PHP?
Tomalak
Yes, but it's not very pretty - link is in the answer
Greg
+1  A: 

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

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?

Paul Dixon