views:

62

answers:

5

I think this may be a stupid question, but I am quite confused whether I need to escape backslash in PHP.

echo 'Application\Models\User'; prints Application\Models\User
echo 'Application\\Models\\User'; same output
echo 'Application\Model\'User'; gives Application\Model'User

So it's a escape character, shouldn't I need to escape it (\) if I want to refer to Application\Models\User?

A: 

Since your last example contains a quote ('), you need to escape such strings with addslashes function or simply adding a slash yourself before it like this:

'Application\Model\\'User'
Sarfraz
+4  A: 

In single quoted strings only the escape sequences \\ and \' are recognized; any other occurrence of \ is interpreted as a plain character.

So since \M and \U are no valid escape sequences, they are interpreted as they are.

Gumbo
A: 

You will find the complete explanation here: http://nl.php.net/manual/en/language.types.string.php

Hollance
A: 

It's optional to escape the backslash, the only exception is when it's behind a single quote (because the backslash escapes the single quote).

See the manual.

Artefacto
A: 

I think it depends on the context, but it is a good idea to escape backslashes if using it in file paths.

Another good idea is to assign the directory separator to a constant, which I've seen done in various applications before, and use it as thus:

<?php
define('DIRECTORY_SEPARATOR', '\\');

echo 'Application'.DIRECTORY_SEPARATOR . 'Models' . DIRECTORY_SEPARATOR . 'User';
?>

If you wish to save space and typing, others use DS for the constant name.

<?php
define('DS', '\\');

echo 'Application'.DS.'Models'.DS.'User';
?>

This keeps your application portable if you move from a Windows environment to a *nix environment, as you can simple change the directory separator constant to a forward slash.

Martin Bean