1

PHP and namespaces.

I assume that i missunderstood its correct usage/idea..
(please read to the end)
I have two files: 1.php, 2.php

1.php:

namespace App\someNS;

class classname{}

2.php:

namespace App;
include_once("1.php");
use App\someNS; // tried to comment it also, not working

$ x = new classname();
// this fails..

My assumption is that namespaces are containers\scope, so by including one - I can access its content;
I expected that the use App\someNS will "include" it.

I know that someNS\classname() will work, but I fails to see the big advantage in namespaces if the only "profit" from them, is the options to use the same names for variables, if after all i still need to use a path to get them... what am i missing?

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
yossi
  • 3,090
  • 7
  • 45
  • 65

2 Answers2

1

Namespaces work like directories and files in your filesystem.

You can enter a directory and execute a file:

cd /var/www/project

phpunit SomeTest

Or you can execute the file passing the whole path:

/var/www/project/phpunit SomeTest

In your example, you can use:

//class2
namespace App;

include_once('1.php');
use App\someNS\classname;

$x = new classname();

Or

//class2
namespace App;

include_once('1.php');
use App\someNS;

$x = new someNS\classname();

Or even

//class2
namespace App;

include_once('1.php');

$x = new someNS\classname();

You can find more details here

Caconde
  • 4,177
  • 7
  • 35
  • 32
1

Namespaces, use and including files are actually three different things:

  • A namespace is just a prefix that allows to reuse the same class and functions names in different parts of your code base.

  • The use statement only creates an alias so you don't need to type the full name (namespace + local name) or you can all the object with a different name. It doesn't import or load code.

  • include is what actually makes code from other files available, but it has existed for years before namespaces were implemented in PHP.

Said that, your code should throw:

Class 'App\classname' not found in ...\2.php

That's because your use alias is for the namespace, so you'd need to call:

new someNS\classname();

To be able to do new classname() you need to alias the class:

use App\someNS\classname;
Álvaro González
  • 142,137
  • 41
  • 261
  • 360