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 用verilog实现tanh函数和softplus函数
  • ¥15 Hadoop集群部署启动Hadoop时碰到问题
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 QTableWidget重绘程序崩溃
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站