FLX
FLX

Reputation: 2679

Php namespace - repeating Use in each class

I have a lot of classes in multiples subfolders that I load using this autoloader :

spl_autoload_register(function ($class) {
    $class = str_replace('\\', DIRECTORY_SEPARATOR, strtolower($class));
    if(file_exists(FILES_PATH.'classes/'.$class.'.class.php')){
        require_once(FILES_PATH.'classes/'.$class.'.class.php');
    }
});

So if i do new Folder\subFolder\Myclass, it works.

The classes in folders are all in a namespace.

All these classes must use the database class, and the problem is here : When the class is in a namespace and search the database class, it can't find it.

(DB class is in global namespace)

So I try to put "use BDD" (Bdd is the db class) and it still doesn't work, because Bdd is using PDO and so i must do "use bdd, pdo;" in EVERY classes of the project...

I find this stupid. Is this normal ? Is there a better way to autoload, without using namespaces ?

Upvotes: 1

Views: 858

Answers (3)

deceze
deceze

Reputation: 522382

It's pretty darn simple:

If you're in a namespace like so:

namespace Foo;

all names of all classes are resolved relative to that namespace. Any Bar will mean the class Foo\Bar, not the "global" Bar. If you want to refer in any way, shape or form to a class which is not in the same namespace, say Bar\Baz (class Baz from the namespace Bar), you have two choices:

  1. use a fully qualified name for the class, e.g.:

    \Bar\Baz
    

    where the leading \ means the class name shall be resolved from the top namespace, not the current local one, or

  2. if this is getting annoying to do every time, alias it using:

    use Bar\Baz;
    

    which is shorthand for

    use Bar\Baz as Baz;
    

    which means any time you use "Baz" in this namespace you mean the class Bar\Baz, not Foo\Bar\Baz.

Yes, this applies to each file individually. If you want to refer to PDO in some namespace in some file, you either have to write \PDO to make it resolve to the "global" PDO class or you write use PDO at the top of the file to make a convenience alias. That's how namespaces work.

This applies to all use cases of any class name:

new \PDO
\PDO::staticMethod()
\PDO::CONSTANT

Upvotes: 2

Elon Than
Elon Than

Reputation: 9765

Moving answer from one of my comments ;)

Using use \Pdo; in BDD class fixed the world :)

Upvotes: 0

Rocket Dendy
Rocket Dendy

Reputation: 31

You can explicitly say that BDD is in the global namespace by doing this in your code:

$foo = new \BDD();

Then you should not need to use it.

Upvotes: 1

Related Questions