tags:

views:

1321

answers:

4

Let's say we have index.php and it is stored in '/home/user/public/www' and index.php calls the class Foo->bar() from the file 'inc/app/Foo.class.php'. I'd like the bar function in the Foo class to get a hold of the path '/home/user/public/www' in this instance - and I don't want to use a global variable, pass a variable etc.

A: 

Found it. getcwd().

RobbieGee
Be aware that any call to chdir() will change the working directory, though.
R. Bemrose
+3  A: 

You can use debug_backtrace to look at the calling path and get the file calling this function.

A short example:

class Foo {
  function bar() {    
   $trace = debug_backtrace();
   echo "calling file was ".$trace[0]['file']."\n";
  }
}
Devon
+1  A: 

getcwd() gets the current working directory

It can be changed for a variety of reasons by 3rd party modules, includes or even your own code by issuing a chdir().

debug_backtrace() as Devon suggested is the answer you're looking for.

Phil
+7  A: 

Wouldn't this get you the directory of the running script more easily?

$dir=dirname($_SERVER["SCRIPT_FILENAME"])
Paul Dixon
You beat me to it.
R. Bemrose
Good call Paul. This will work most of the time. It is possible, though, that you could have something that includes index.php. For example, special.php includes index.php which includes inc/app/Foo.class.php. This is rare, but possible.
Devon
Huh, I thought that didn't work if you called the script from the command line, but it does!
RobbieGee