tags:

views:

52

answers:

2

My situation: I have a class that I want to use in a number of places, so I placed it high in the directory tree:

/www/libs/classA/classA.php

It uses a config file located in the same directory called config.ini and references it locally in the constructor. However, when I include it from a script in a different directory, it tries to load the config file from the directory the calling script is in. Is there any way I can look in the directory the included file is in? Ideally I could move the script to a different directory and not make any changes to it.

+4  A: 

You should use the absolute path when including/loading files. And you can retrieve that absolute path with the __FILE__ constant and dirname function:

dirname(__FILE__).'/config.ini'

This will five you the absolute path of the config.ini file in the same directory the currently executed script file is located in. So when that code is executed in your classA.php script file, you would get /www/libs/classA/config.ini.

Gumbo
A: 

You should be able to include/require a file from the current file's directory if you have no path info in the argument, e.g. include('file2.php');. But I think even if you have './file2.php'), then it's going to become relative to the directory of the first-included/executed script.

I like the dirname(__FILE__)... method, but I believe in the case where a certain set of files is intended to always be deployed in the same directory, the direct file include promotes cohesion.

grantwparks