3

I'm trying to include many files containing functions, classes and calls but I would like to put everything in a PHP namespace. My issue is : all the files are part of another web application core. So I cannot edit the files. Is there a way tu declare a namespace globally for a list of files ? Something like that :

namespace mynamespace {
    include_once("file1.inc.php");
    include_once("file2.inc.php");
    include_once("file3.inc.php");
    ...
}

Of course I tried this code and it does not work; all my tries failed while the first line of the include files where note namespace mynamespace;.

2 Answers 2

3

No, it is not possible. Every single file needs to declare its own namespace; you cannot force something to be in a different namespace using external code. (Some hacks like runkit or such will probably allow you to fiddle with that, but I'd consider this outside the regular scope of PHP as a language.)

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

2 Comments

Seems logic but I thought that if you can include a file, you could be able to set its namespace. Thanks a lot for your fast answer!
Think of namespaces as being part of the class's/function's name. Then maybe it's more obvious that you can't willy nilly rename things.
0

Yes. A bit cumbersome (you need to list all classes) and works only if you have well behaved files that start with <?php and don't have a namespace in them. Also, because there's no decent error-reporting in eval'd stuff, use it only with well tested code.

<?php

namespace whatever;

use mynamespace\Class1FromFile1;
use mynamespace\Class2FromFile1;
use mynamespace\ClassFromFile2;
use mynamespace\ClassFromFile3;

function ns_inc ($lib, $ns) {
        eval("namespace $ns;" . substr(file_get_contents($lib), 5));
}

$ns= 'mynamespace';
ns_inc('file1.inc.php', $ns);
ns_inc('file2.inc.php', $ns);
ns_inc('file3.inc.php', $ns);

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.