Pacerier
Pacerier

Reputation: 89703

Can the namespace statement be "included" in PHP?

I have a file which looks like this:

<?php
namespace n;
f(); // this calls n\f()

PHP statements can be included by using the include function, however, this doesn't work for the namespace statement:

<?php
include('example_include_namespace_statement.php')
f(); // this doesn't call n\f()

example_include_namespace_statement.php:

<?php
namespace n;

Is there any way to "include" the namespace statement in PHP?

Or is it simply not possible?

Upvotes: 0

Views: 39

Answers (1)

Sverri M. Olsen
Sverri M. Olsen

Reputation: 13283

You have to specify the namespace when calling a function that is in a namespace, like so:

// test.php
namespace test;
function doesItWork() {
    return 'It Works!';
}
// index.php
include 'test.php';
echo test\doesItWork();

If you want to use a function that is defined in a namespace that is outside the current namespace then you must prefix it with the namespace character, like so:

echo \test\doesItWork();

You should read the documentation on namespaces.

Upvotes: 2

Related Questions