15

I have a file that require()'s a namespace, as such:

<?php
require_once('Beer.php');   // This file contains the Beer namespace

$foo = new Beer\Carlsburg();
?>

I would like to put the Beer namespace directly in the same file, like this (unworking) example:

<?php
namespace Beer {
    class Carlsburg {}
}

$foo = new Beer\Carlsburg();
?>

However, the PHP interpreter complains that No code may exist outside of namespace. I can therefore wrap $foo declaration in a namespace, but then I must also wrap Beer in that namespace to access it! Here is a working example of what I am trying to avoid:

<?php
namespace Main\Beer {
    class Carlsburg {}
}

namespace Main {
    $foo = new Beer\Carlsburg();
}
?>

Is there any way to include the code for the Beer namespace in the file, yet not wrap the $foo declaration in its own namespace (leave it in the global namespace)?

Thanks.

1
  • You should have Heineken as namespace! Commented Jun 4, 2014 at 19:58

4 Answers 4

21

You should use the global namespace :

<?php
namespace Beer {
    class Carlsburg {}
}


namespace { // global code
    $foo = new Beer\Carlsburg();
}
?>

See here -> http://php.net/manual/en/language.namespaces.definitionmultiple.php

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

1 Comment

This wont work unless you write $foo = new Main\Beer\Carlsburg();
4

Try this

namespace Beer {
  class Carlsburg {}
}

//global scope 
namespace {
  $foo = new Beer\Carlsburg();
}

As per example #3 in Defining multiple namespaces in the same file

Comments

3

Try placing a backslash before the namespace name:

$beer = new \Beer\Carlsberg();

The initial backslash is translated to "global namespace". If you do not put the leading backslash, the class name is translated to the current namespace.

Comments

3

Just write it, it has no "name":

<?php
namespace Main\Beer {
    class Carlsburg {}
}

namespace {
    use Main\Beer;
    $foo = new Beer\Carlsburg();
}
?>

Demo and see Defining multiple namespaces in the same fileDocs.

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.