user1821218
user1821218

Reputation: 243

PHP dynamically generate namespace based on folder structure

I have a folder structure like so:

index.php
app/
    controllers/
                folder1/
                        class.php

There is no namespace definition in class.php. Would it be possible to put class.php in a namespace generated from folder structure relative to index? So it would be loaded like:

new \app\controllers\folder1\classInFile();

Or is there no way to dynamically create namespaces?

Upvotes: 1

Views: 878

Answers (3)

eisberg
eisberg

Reputation: 3771

The namespace needs to be defined inside of class.php if you can create the PHP source file dynamically, you can create the namespace dynamically.

Upvotes: 0

deceze
deceze

Reputation: 522382

A file containing a namespace must declare the namespace at the top of the file before any other code.

http://php.net/manual/en/language.namespaces.definition.php

I.e., you cannot execute any code before the namespace declaration, and afterwards it's too late. Notwithstanding introspective runtime hacks: no, it's not possible. Even if it was, it would depend on runtime information, like what folder the code is executed/included from. The namespace could be var\www\myproject\foo\bar\baz or just foo\bar\baz. How are you going to determine that? That's getting messy.

Really, just make it explicit, even if that means typing a little more. The namespace is part of the class's name. You should not generate names dynamically at runtime.

Upvotes: 2

bear
bear

Reputation: 11625

You shouldn't be dynamically generating namespaces, the namespace cannot be set and read at compile time.

In any case, the namespace is provided/defined before any code is executed.

Upvotes: 0

Related Questions