Jimmyt1988
Jimmyt1988

Reputation: 21126

PHP namespaces, I just don't get it

Say I have a folder with some files in them:

Inside each file I have declared the namespace like so:

Database.php

namespace Infrastructure\Core
{
    class Database
    {...}
}

Model.php

namespace Infrastructure\Core
{
    class Model
    {...}
}

etc...

Now I want to use all classes in that namespace. Imagine I have the following root file

index.php

use Infrastructure\Core

class Main
{
    $database = new Database();
    $controller = new Controller();
    //...etc..
}

This is almost like java and C# namespacing, but obviously in PHP it doesn't work... So the following doesn't work either:

index.php

use Infrastructure\Core

class Main
{
    $database = new Infrastructure\Core\Database();
    $controller = new Infrastructure\Core\Controller();
    //...etc..
}

Does not work either, so I finally think, okay I have to include the files too then... still doesn't work.. What am I doing wrong? I really do not get the millions of examples as it seems so different from any other namespacing I've used before.

Can someone provide an example specific to this one with the correct syntax so I can latch on to what it's all about with PHP. I assume it's a slightly different concept in php?

Upvotes: 0

Views: 132

Answers (2)

Carlos487
Carlos487

Reputation: 1489

Namespaces are a logical separation for your code the \ doesn't necesary means a folder path.

I haven't programmed in PHP in some time but I think you are not using include or another mechanism to include the file contents.

Upvotes: 0

Nanne
Nanne

Reputation: 64399

A couple of things:

  1. your classes need to be loaded, so you either build yourself an autoloader based on classname // dir-name, or you manually include the correct files (so with include and/or require

  2. 'use' is just for 'shortcuts', forget about that now

  3. while your namespace declaration is correct, you have to call them from the 'root', so they start with a \

    $database = new \Infrastructure\Core\Database();
    

Upvotes: 6

Related Questions