Search code examples
phpphpunitrequire-once

require_once not working as I expect it to


Possible Duplicate:
relative path in require_once doesn’t work

I have a project structure as such:

ProjectName/
   src
     test
       TestClass.php
   tests
     TestTestClass.php

WhenI try and do require_once '/ProjectName/src/test/TestClass.php'; into tests/TestTestClass.php I get an error from PHP stating that: no such file or directory.

I have checked the spelling, I have checked everything. I cannot give it the full /home/userName/bla/bla path as I need to hand this off to some one else.

Any ideas?


Solution

  • This is expected behaviour. When you execute TestTestClass.php, your working directory is set to ProjectName/tests.

    It would be better to use ../src/test/TestClass.php.

    Your path is actually absolute, so you will be working straight from /, which is not what you're expecting. If your include_path is set to your server's directory root, then your code will work without the first /. If you don't wish to rely on include_path or arbitrary levelling (with ..), you can always set an environment variable in your first file that defines the full path to your application root, then use that for all includes.

    For example, /ProjectName/index.php:

    define('APPPATH', __DIR__);
    

    .. and in /ProjectName/tests/TestTestClass.php:

    require_once APPPATH . '/src/test/TestClass.php';