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

时间:2013-12-13 17:04:00

标签: php oop constants

我的具体情况是我试图将路径定义为常量。现在我硬编码:

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

但我需要将define定义为可移植的。因此可以检测路径,放入变量,然后放入类中。基本上,我想要完成的是:

$somepath = {code to get path};

class Cache 
{
const PATH_TO_CACHE = $somepath;

2 个答案:

答案 0 :(得分:6)

我喜欢使用依赖注入。例如:

class Cache {

  private $path_to_cache;

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

}

然后您可以使用已定义的设置:

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

您还可以在开发/调试时轻松更改路径:

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

答案 1 :(得分:1)

实际上有一个解决方法:

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];
        }
    }
}

基本上你创建一个带有键作为常量的数组,这样你就可以像这样得到那个值:

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

我的猜测是你打算强制类的用户通过常量值访问该路径。 但是,如果只有一个常量,则不应使用此方法,它会超出数组的目的。