0

In python you can do "import star" to embed everything from another namespace into the local one:

# file "spam":
def ham():
    some code

# file "main":
from spam import *
xy = ham() <-- uses 'ham' from 'spam'

This is usually considered "bad practice", but I'm still wondering how to do the same with php namespaces. The following doesn't work:

# file "spam":
namespace spam;
function ham() {
    some code
}

# file "main":
include "spam.php";
use spam;    
xy = ham() <-- error
georg
  • 211,518
  • 52
  • 313
  • 390
  • That's strange... i do it everyday and it works everytime. Making a page a.php with function (or public function) a, include it into page b.php and calling the a function. – Goikiu Dec 30 '13 at 09:49
  • @Goikiu: good point, but I'd like to keep "spam" namespaced, so that whoever uses it has a choice. – georg Dec 30 '13 at 09:55
  • *"Neither functions nor constants can be imported via the use statement."* - http://php.net/language.namespaces.faq#language.namespaces.faq.nofuncconstantuse – hakre Dec 30 '13 at 10:23

2 Answers2

2

In PHP you do not "import from" a namespace. You can only alias a namespace or class to another (presumably shorter) name. So typically you do this:

use Foo as F;

new F\Bar;

That's the PHP "equivalent" to "using everything from a namespace as conveniently as possible".

deceze
  • 510,633
  • 85
  • 743
  • 889
1

While there is no way to include all classes in a namespace with a single line, the way one can with just about any other language, I find it endlessly helpful to have an IDE handle the "use" cases automatically.

I highly recommend looking into PhpStorm (it's my personal favorite). It does a wonderful job automatically writing the "use" lines when using the auto-complete features.

See https://www.jetbrains.com/phpstorm/webhelp/creating-imports.html

georg
  • 211,518
  • 52
  • 313
  • 390
NeoNexus DeMortis
  • 1,286
  • 10
  • 26