I’m using symfony and trying to reference a file that’s in a parent directory like so:
require_once('../MyClass.class.php');
It doesn’t seem to be working though it keeps saying it can’t find the file when I run the task. I tried the same code on my personal WAMP server (as opposed to going through this server) and that doesn’t use symfony and it worked fine.
I’m not sure why symfony can’t find it?
Thanks
When you
includea relative path, the path is relative to the “top-level” script – that is, the entry point to the application – rather than the script currently being executed.When dealing with frameworks, the entry point is often a file at the top of your web root called
index.php. For this example, we’ll assume this file is~/application/index.php.Your index.php file will necessarily include files from other parts of your framework, and it’s in one of these that you’re likely attempting to perform your include. Lets say that you’re attempting the include from a controller file. We’ll give it the filename
~/application/controllers/example.php.Now, what you think is happening when you do
include "../MyClass.class.php"is that you think that the filename will be one level above the script that’s currently executing – i.e. you think that since you’re in~/application/controllers/example.php, the parent directory will be~/application/controllers, so you’ll include~/application/MyClass.class.php.What will actually happen, is the relative path will be determined based on the location of the entry point,
~/application/index.php, so the parent directory will be~/, and PHP will attempt to include the file~/MyClass.class.php, which doesn’t exist.I don’t know Symfony, so I don’t know how it’s autoloader works, but you should be able to call a framework function to load your class for you. If you really must
includethe file manually, then you need to include the file relative to the index.php file. Most frameworks have constants (e.g.BASEDIR) that you can use to easily generate an absolute path.There are also two PHP-defined constants you can use for this:
__FILE__will give the script-name for the currently executing script (not the main/top-level one as above), so you can usedirname(__FILE__)to get the current directory, or something likedirname(dirname(__FILE__))to get the parent directory.__DIR__(for PHP >= 5.3.0) will give you the directory of the currently executing script, so you can usedirname(__DIR__)to get the parent directory.Again, your framework can likely handle this for you, but it’s good to know for when you’re dealing with non-framework scripts.