简体   繁体   中英

PHP is it possible to extend a namespace to natively use functions outside of class

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 ....
  }
}

I don't see how you could use functions inside a class, even if they are in the same one without $this-> or $object-> . The solution I could provide very roughly is instantiating the Base class, if you are not able to extend it (a class named Base seems like one which should be extended, but anyaways):

namespace Core\Config;

class Config{

  private $_base;

  public function __construct($array){
    $this->_base = new Core\Base();
    $conf = $this->_base->get($array, 'key1.key2.key3');

Or, wrap them:

class Config {

    public function get($array, $path=null) {
        $base = new Core\Base();
        return $base->get($array, $path);
    }

    public function __construct($array) {
        $conf = $this->get($array, 'key1.key2.key3');
    }

OK, Now I see, they are functions in a file, which contains class.

namespace Core\Config;
use Core;
class Config {
    public function __construct($array) {
            $conf = Core\get($array, 'key1.key2.key3');
        }

Or for minimzing the work, you can alias gore as C for example

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM