Is using the directory separator constant necessary?

Viewed 17166

I am using PHP, but I guess this question might be language agnostic.

With PHP, a constant is defined by PHP, called DIRECTORY_SEPARATOR. I have seen this in Joomla

define('DS', DIRECTORY_SEPARATOR);

I thought this looked like a good idea so I incorporated it into some of my sites. Now I'm asking myself why. I have only experience on Windows and OS X and from what I know Microsoft, Linux and Apple all use the forward slash as the directory separator.

Is using this constant unnecessary?

4 Answers

Mac OS Classic uses ":", for instance. See Wikipedia for details. Also it's considered good style avoiding 'magic numbers' or similar constructs.

Windows actually uses a backslash as the directory separator, although some environments that have Windows versions will translate between forward slashes and backslashes automatically (Python comes to mind).

I learned that the best way to write cross-platform compatible code is to never use DIRECTORY_SEPARATOR, or backslashes \\, and to ONLY use forward slashes /.

Why? Because a backslash directory separator ONLY works on Windows. And forward slashes works on Linux, Windows, Mac altogether.

Using the constant DIRECTORY_SEPARATOR or escaping your backslashes \\ can become messy. Look at this example:

$file = 'path' . DIRECTORY_SEPARATOR . 'to' . DIRECTORY_SEPARATOR . 'file';
$file = str_replace('/', DIRECTORY_SEPARATOR, 'path/to/file';
$file = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? 'path\\to\\file' : 'path/to/file';

When you can just do this:

$file = 'path/to/file';

The only downside I came across is that PHP will return backslashes on Windows for all file references from functions like realpath(), glob(), and magic constants like __FILE__ and __DIR__. So you might need to str_replace() them into forward slashes to keep it consistant.

$dir = str_replace('\\', '/', realpath('../'));

I am hoping that PHP in the future will introduce some php.ini setting to always return forward slashes.

Related