Skip to content

PHP Development Tricks

timoahummel edited this page Sep 15, 2010 · 4 revisions

PHP Development Tricks

This page lists some PHP development tricks.

Using dirname instead of complex path manipulations

I often see something like dirname(__FILE__) ."../../../src/foo/bar.php" or even more complex operations on directory names. It is not only hard to read, but also can cause problems. I prefer to use multiple invokations of dirname to "change" to the higher-level directory. For example, if your file is in src/lib/foo.php and you need to include 3rdparty/lib/bar.php, you can simply use dirname(dirname(dirname(__FILE__))) from inside foo.php. With that mechanism, it is also easy to implement a function:

<?php
function getParentDir ($dir, $levels = 0) {
	if ($levels == 0) { return $dir; }
	--$levels;

	$dir = dirname($dir);

	if ($levels > 0) {
		return getParentDir($dir, $levels);
	} else {
		return $dir;
	}
}

echo getParentDir(__DIR__, 1);

Omitting the closing PHP tag

In recent PHP versions (or: probably since ever?) you can omit closing PHP tags at the end of your files, avoiding unnecessary whitespaces and probably confusion of your browser, especially if you plan to send headers() somewhere in your code.