doumi4676 2013-11-04 11:29
浏览 18
已采纳

PHP可以将命名空间扩展为本机使用类外的函数

Okay here is the scenario:

Here are two example classes.

  1. The first one defines some functions outside the class name.
  2. I would like the second class to be able to implement it as if it was defined natively.

There are a couple of functions I use a lot.

I thus need them to be as short as possible for readability and writing speed.

If i could stick them in a namespace and extend it in some way, it would also prevent possible conflicts in other libraries.

Base class

namespace Core;

class Base{
  ......
}

function set($array, $path=null, $value=null){
  .....
}

function get($array, $path=null){
  .....
}

Second Class

namespace Core\Config;

class Config{
  public function __construct($array){
    $conf = get($array, 'key1.key2.key3');
    .... do something with returned value ....
  }
}
  • 写回答

2条回答 默认 最新

  • doumu2172 2013-11-04 11:45
    关注

    Someone suffested that already but not in the right way:

    <?php
    namespace Base {
        function get() {...}
    }
    
    namespace Base\Config {
        use \Base as B;
    
        class Config {
            public function __construct(...) {
                $something = B\get(...);
            }
        }
    } 
    

    You can import and alias the Base namespace and use it.
    However, you cannot import a function or constant (only classes and interfaces)

    Reference: PHP.net


    Also note, that you cannot define a function in a class outside the class name.
    What you are doing is defining a class and several "stand-alone" functions in one file, but they do not relate in an way (they are in the same namespace, though).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程