简体   繁体   中英

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.

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