0

I've seen a very similar question (and answer) here: https://stackoverflow.com/a/20933938/339440 ...but it doesn't quite do what I need.

I have this:

<?php
namespace My\Project {
    function foo() {
        ...do stuff...
        return $something;
    }
}

namespace {  // global namespace
    function prefix_foo() { return My\Project\foo(); }

}

What I want in the global namespace is this:

namespace {
    use function My\Project\foo as prefix_foo;
}

...but any time I try to call prefix_foo() in the global namespace I get a "function not defined" error. I'm using PHP 5.6.25. Can anyone tell me why this doesn't work? It appears that this works just fine without the "as" (per the linked question above).

EDIT: Okay, I figured out that it's happening because the definitions and the actual usage are happening in two different files. It appears you have to put the "use" clause in each individual file that might use the functions.

This would be really unwieldy in this case, as I have to "define" a whole bunch of functions this way and repeating a giant block of use clauses in each one would defeat the purpose.

Is there a way to have the "use" statement work from one PHP file to the next (via include)?

7
  • It does work eval.in/642475 Commented Sep 14, 2016 at 17:12
  • 1
    Hm... so it does. That actually helped. Please see the edit above. Commented Sep 14, 2016 at 17:20
  • No, the use statement is only valid for the file it is in. Instead of importing the function as a prefixed function, just use My\Project\foo at it is. I'm not even sure why you try to do that. Commented Sep 14, 2016 at 17:31
  • To save a bunch of typing and increase readability. These functions are called quite a lot. (It's more than one function....) Commented Sep 14, 2016 at 17:45
  • Thank you, Charlotte. Helpful even if not what I wanted to hear. ;-) Commented Sep 14, 2016 at 17:49

1 Answer 1

0

Answered my own question, and it turns out the question itself wasn't what I thought it was.

I had the definitions and the actual usage in two different files. You have to put the "use" clause in each individual file that might use the functions.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.