0

Lets suppose I have some classes in the global namespace. I don't want to use the namespace keyword in each class, but I have an autoloading mechanism. Can I dynamically set the namespace for the classes? So

\src\HTML\Form\Form.php

// namespace HTML\Form

class Form
{
}

\src\Setting\Db.php

// namespace Setting

class Db
{
}
4
  • Why do you want to do such a thing? Commented May 27, 2015 at 13:59
  • I dont need to manually put a correct namespace definition to about 200 file. Namespace fit to directory structure anyway, so it can be automatized Commented May 27, 2015 at 14:01
  • Most people do the reverse: the namespaced classname maps to the folder (as per PSR-4).... but adding a namespace keyword to 200 files isn't a lot Commented May 27, 2015 at 14:06
  • yes but what if I move a sub-directory to another? Doing renaming manually again? Commented May 27, 2015 at 14:25

1 Answer 1

2

I dont want to use the namespace keyword in each class

If you don't want use namespace, then don't use it. If your problem is only to use an autoloader then you can simply map each class with its directory path.

$srcDir = __DIR__. '/src';
$formDir = $srcDir . '/HTML/Form';
$classesMap = array(
    'Db'   => $srcDir . '/Setting/Db.php',
    'Form' => $formDir . '/Form.php',
); 

This work would not be necessary if you followed one standard like PSR-0/4 or the (old) PEAR coding standard.

If you're using composer, look classmap.

is there a way to load a class into a namespace?

Something like

function autoload($class) {
    namespace DynamicNamespace {
        require ('/path/to/classes/'. $class);
    };
}

is not allowed.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.