d_inevitable
d_inevitable

Reputation: 4461

PHP Root namespace

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.

Upvotes: 3

Views: 4564

Answers (2)

Lewis
Lewis

Reputation: 622

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

Upvotes: 0

Cerad
Cerad

Reputation: 48865

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.

Upvotes: 4

Related Questions