Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between '\' and '\\' in symfony2 registerNamespaces?

Tags:

php

symfony

What is the difference between these two code snippet. First one with \ and second one with \\.

First One:

<?php
// File: app/autoload.php
$loader->registerNamespaces(array(
    'Knp\\Component'      => __DIR__.'/../vendor/knp-components/src',
    'Knp\\Bundle'         => __DIR__.'/../vendor/bundles',
    // ...
));

And second one:

<?php
// File: app/autoload.php
$loader->registerNamespaces(array(
    'Knp\Component'      => __DIR__.'/../vendor/knp-components/src',
    'Knp\Bundle'         => __DIR__.'/../vendor/bundles',
    // ...
));

Are they different or do they work the same?

like image 632
pmoubed Avatar asked Dec 06 '25 10:12

pmoubed


1 Answers

The backslash has a special meaning in double quoted strings: it's used for escaping various characters (such as \n and \r).

In single quoted strings the backslash is used for escaping the literal quote (eg echo 'I\'m';) and the backslash itself.

It is better practice to use double backslashes in namespace strings to prevent any possible errors due to character escaping. Other than that, they are the same thing:

// outputs: Foo\Bar\Baz
echo 'Foo\Bar\Baz';

// outputs: Foo\Bar\Baz
echo 'Foo\\Bar\\Baz';

// The autoloader would not be able to find the correct file
// outputs: Foo
//          ot    hat
echo "Foo\not\that";
like image 189
kgilden Avatar answered Dec 08 '25 01:12

kgilden