我的具体情况是,我试图定义一个常量的路径。现在我硬编码如下:
class Cache
{
const PATH_TO_CACHE = '/home/site/public_html/wp-content/themes/theme/cache/';
但我需要这个定义是可移植的。因此,可以检测路径,将其放入变量中,然后放入类中。从本质上讲,我想完成的是:
$somepath = {code to get path};
class Cache
{
const PATH_TO_CACHE = $somepath;
我喜欢为此使用依赖项注入。例如:
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');
实际上有一个解决方法:
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);
我的猜测是,您打算强制类的用户通过一个常量值访问该路径。然而,如果只有一个常量,就不应该使用此方法,因为它超出了数组的用途。