1

Hey I am new to php namespaces and I'm trying to make sense of something. I am following the PRO Php MVC e-book and they use a lot of namespace examples in there code. What's confusing me is the difference between \Framework\Name and Framework\Name?

When do you use which version and what is the difference between them.

1 Answer 1

3

Its really a difference of where its being used in the code.

For example, in a use statement, either can be used:

<?php
namespace Framework;

use Framework\Name;
// OR
use \Framework\Name;
// Both do the same thing

However, when you are actually in the code, not having the \ in the front of the namespace, will make the code look in the current namespace for the file. Example:

<?php
namespace Framework;
// ...
// The below will actually look for the class `\Framework\Framework\Name`
$class = new Framework\Name();
// However, this will look for, and hopefully find `\Framework\Name`
$class = new \Framework\Name();

This lets you do things like have a use statement on a subnamespace, and shorten your calls in the code: Example

<?php
namespace Framework;
use Framework\Cache;

class test {
    public function __construct() {
        // Below gets `\Framework\Cache\Memcache`
        $memcache = new Cache\Memcache();
        // Below gets `\Framework\Cache\Apc`
        $apc = new Cache\Apc();
    }
}

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.