3

I have got a single file in which I need specify classes in multiple namespaces, something like:

<?php

namespace library;

class ClassInLib {
   ...
}

namespace \; //Switch to root namespace

class ClassInRoot {
   ...
}

The above code has a syntax error at namespace \;. How can I switch from the library namespace to the root namespace?

Why do I need this: I need to mock a bunch of classes during unit testing and I don't think these very short mock classes justify being in separate files.

2 Answers 2

4
namespace 
{ 
    class RootClass
    {

        function whatever();
    }
}
namespace Symfony\Component\DependencyInjection
{
    interface ContainerAwareInterface
    {

        function setContainer(ContainerInterface $container = null);
    }
}

http://www.php.net/manual/en/language.namespaces.definitionmultiple.php

Good chance you will decide to use separate files anyways.

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

1 Comment

Hey Thanks, this answer would do, only that the root namespace would need to be used after the library's namespace to really preempt the autoloader, but yea it works the other way round too.
0

I struggled with this for a while - I put the class files I wanted to be global namespaced ( e.g. I want to use them as \myClass ) into their own folder and I removed any namespace ... ; declared in the files.

Then in composer.json add in classmap to the directory I'd made:

    "autoload": {
        "classmap": [
            "directoryWith/subDirIfNeeded"
        ]
        ...
    } 

Then don't forget to composer dumpautoload whenever you make a change to composer.json

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.