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.
views:
1321answers:
4Be aware that any call to chdir() will change the working directory, though.
R. Bemrose
2008-09-26 14:24:19
+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
2008-09-26 14:21:31
+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
2008-09-26 14:23:31
+7
A:
Wouldn't this get you the directory of the running script more easily?
$dir=dirname($_SERVER["SCRIPT_FILENAME"])
Paul Dixon
2008-09-26 14:27:36
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
2008-09-26 14:53:00
Huh, I thought that didn't work if you called the script from the command line, but it does!
RobbieGee
2008-09-27 14:01:32