What is dirname(__FILE__) about?

The old Slaptech framework had the old PHP includes problem, where one cannot to include() a file relative to the current file. All include() paths are assumed to be relative to the first PHP file that's opened in the browser.

So, if you have a file ./index.php, and a library lib/foo.php, and in lib/ there's another file lib/sub/tool.php, you can't write "include 'sub/tool.php';" in foo.php.

That really messes with inclusions. The solution we came up with was that the file index.php would have to define a variable $global_base (yes, lame name), and it would usually have a value like "./" or "../" that would be the path to the application's root directory.

Then, in the classes, you'd have include statements like:

include_once $global_base."core/Database.class.php";

We weren't hip to the solution others were using: dirname(__FILE__). You would instead use code like this:

include_once dirname(__FILE__)."/core/Database.class.php";

The problem with that is that it causes a call to dirname(), which can't be that fast. See these articles.

The issue is discussed at PHP 10.0 and Don't Abuse dirname(__FILE__).

Both styles of specifying paths also suffer from a problem with VIM, because you can't use "gf" to "goto file", a feature in VIM where you can open a file by typing "gf" over the filename.

The dirname(__FILE__) technique fails because, while the path is relative to the current file, the path starts with "/", fouling up VIM's "gf". Fixing that is simple but wastes even more CPU.

The $global_base style fails because the path is always rooted in the application's base directory. To make it work, you have to add the app's root to the VIM path. You also need to start the path with a the directory name, not "/".

The best solution would be if PHP had a new include_once or require_once statement that would perform the include from the current file's directory, and forego looking through "path" for anything. For speed, it should also require the string to be a constant. That way, the path can be checked at compile-time.

load 'path/to/file.php';

My thinking is that the layout of your files is pretty inflexible. That's just how code is today. It's rare when a program produces some code, adding code to the system. And it's even rarer that the generated code is moved around the filesystem during runtime. In fact, I've never seen it done. It *can* be done, but I've never seen it.

.

Donate Bitcoin to support the writer: 1F13NCPcFKjJ7oy36zc2vBTtqoQCBPpAPH

Comments are disabled

If you wish to comment, post this article on reddit or hacker news.