• Home
  • Blog
  • Demos
  • About
  • ------------------
  • Articles
  • Csharp(59)
    • controls (4)
    • methods (5)
    • tutorials (50)
  • Html(1)
    • tutorials (1)
  • Java(10)
    • mobile (10)
  • Javascript(5)
    • tutorials (5)
  • Linux(3)
    • tutorial (3)
  • Math(10)
    • tutorials (10)
  • Php(15)
    • functions (1)
    • mysql (6)
    • tutorials (8)
  • Sql(23)
    • tutorials (23)
  • Vba(1)
    • tutorials (1)

Require_once using dirname

Written: 2010-02-05 06:55:54
Mood: Happy
Subject: programming
Right!

I've been somewhat frustrated the last few days since I was building a small class library in PHP. The problem I has was that the various files resided in different directories in the class dir.

There could be one file:

/root/lib/foo/someFile.php

And then there could be

/root/lib/otherFile.php


The problem I faced was when someFile.php was depending on otherFile.php. Normally you would do the following:

require_once('../otherFile.php');


This way you would have the file required and everyone would be happy. The problem was that if someFile.php in turn was required in another file that resided in another dir, the current path from which it searches when requiring was changed, for example:

/root/lib/see/saw/whatFile.php

If whatFile.php requires someFile.php and someFile.php runs require_once('../otherFile.php') it will look for otherFile.php in the /root/lib/see/ directory.


To overcome this problem I searched the web like a maniac and finally, via php.net, dreamincode.net and extensive IRC debate, the solution was found:
require_once(dirname(__FILE__).'/../otherFile.php');


when using __FILE__ inside require_once you get the filename of the file you're in (in this case someFile.php) and not the file that is running (in this case whatFile.php).

That's great news and it solved my problem!