Do I need to escape backslashes in PHP?

Do 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 an escape character. Shouldn't I need to escape it (\) if I want to refer to Application\Models\User?


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.


In single quoted strings, it's optional to escape the backslash, the only exception is when it's before a single quote or a backslash (because \' and \\ are escape sequences).

This is common when writing regular expressions, because they tend to contain backslashes. It's easier to read preg_replace('/\w\b/', ' ', $str) than /\\w\\b/.

See the manual.


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

'Application\Model\\'User'