douzhe9927 2016-09-14 17:02
浏览 54

PHP:别名使用“as”在另一个命名空间中定义的函数

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)?

  • 写回答

1条回答 默认 最新

  • dongzi0857 2016-09-16 14:53
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?