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 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输