简体   繁体   English

PHP OOP-如何用变量或函数输出定义CONST?

[英]PHP OOP - How do I define a CONST with a Variable or Function Output?

My specific case is that I am trying to define a path into a constant. 我的具体情况是我试图将路径定义为常量。 Right now I hard code as such: 现在,我这样硬编码:

class Cache
{
   const PATH_TO_CACHE = '/home/site/public_html/wp-content/themes/theme/cache/';

But I need the define to be portable. 但是我需要定义是可移植的。 So the path can be detected, put in a variable, then put in the class. 因此可以检测路径,将其放入变量中,然后放入类中。 Essentially, what I want to accomplish is: 基本上,我想要完成的是:

$somepath = {code to get path};

class Cache 
{
const PATH_TO_CACHE = $somepath;

I like to use dependency injection for this. 我喜欢为此使用依赖项注入。 For example: 例如:

class Cache {

  private $path_to_cache;

  function __construct($cache_path) {
    $this->path_to_cache = $cache_path;
  } 

}

Then you can use a defined setting: 然后,您可以使用定义的设置:

$cache = new Cache($GLOBALS['config']['cache_path']);
$cache = new Cache($_SERVER['cache_path']);
$cache = new Cache($some_other_way_to_get_cache_path);

etc. 等等

You can also easily change the path when developing / debugging: 您还可以在开发/调试时轻松更改路径:

$cache = new Cache('path/to/folder/that/is/being/problematic');

Actually there is a workaround for this: 实际上有一个解决方法:

class Cache 
{
    const PATH_TO_CACHE = 'whateverYouWantToNameIt';

    private $_config = array(
        self::PATH_TO_CACHE => ''
    );

    public __construct() {
        $somePath = 'construct this path by your rules';
        $this->_config[self::PATH_TO_CACHE] = $somepath;
    }

    public function getConfig($configKey)
    {
        if (array_key_exists($configKey, $this->_config)) {
            return $this->_config[$configKey];
        }
    }
}

Basically you create an array with a key as a constant and this way you can always get that value like so: 基本上你创建一个数组,其中一个键作为常量,这样你总是能得到这样的值:

$cacheObj = new Cache();
$somePath = $cacheObj->getConfig(Cache::PATH_TO_CACHE);

My guess is that you intend to force the users of the class to access that path via a constant value. 我的猜测是你打算强制类的用户通过常量值访问该路径。 However this method shouldn't be used if you only have one constant, it beats the purpose of an array. 但是,如果只有一个常量,则不应使用此方法,它会超出数组的目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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