phppathphpunitrelative-pathrequire-once

PHP require_once error with relative path


I would like to test my php application in phpunit. My problem is the require_once doesn't find the file what I would like to test. I get this error:

Warning:
require_once(C:\MyProject\phpunit-tesztek\include/../include/form.php):
failed to open stream: No such file or directory in
C:\MyProject\phpunit-tesztek\include\FormTest.php on line 4

So it search the form.php file in include/../include/form.php what is wrong.

I used this code:

require_once 'PHPUnit/Autoload.php';
require_once(__DIR__.'/../include/form.php');

the Test file is in C:\MyProject\phpunit-tesztek\include\FormTest.php

and the file what I want to test is in: C:\MyProject\include\form.php

What is the problem?


Solution

  • The problem is the relative path. The __DIR__ uses the directory the file is in without a trailing separator. You are then changing the path with a relative path (/../) to go up one directory.

    See the manual entry -> PHP Manual for __DIR__

    __DIR__ will return C:\MyProject\phpunit-tesztek\include
    

    You are looking to use the C:\MyProject\include\ path

    __DIR__ . '/../../include/Form.php';
    

    I normally use the dirname(__FILE__) myself, as it gets the current directory of the source code file (which is absolute) allowing my relative path to move from that location.