我有一個靜態方法的類。該靜態方法返回一個私有的靜態stdClass對象。PHP靜態類返回引用
myclass::get() // returns stdClass object
myclass::get()->name // name is hardcoded into the class
我怎麼會更改名字的價值,如:
myclass::get()->name = 'bob';
,並把它設置?
我試圖返回對象,如:
return &self::$static_object;
但拋出語法錯誤。
我該怎麼辦?
編輯發佈代碼澄清
final class config {
private static $configs = array();
public static function get($config_name) {
if (isset($configs[$config_name])) {
return self::$configs[$config_name];
}
$file = __get_file_exists(M_CONFIGS . $config_name, 'conf.');
if ($file) {
$config = self::__scope_include($file);
if (!is_array($config) && !$config instanceof stdClass) {
/*
*
*
* FIX
*
*
*
*/
die('ERROR config.php');
}
return self::$configs[$config_name] = self::__to_object($config);
}
}
private static function __scope_include($file) {
return include $file;
}
private static function __to_object($config) {
$config = (object) $config;
foreach ($config as &$value) {
if (is_array($value)) {
$value = self::__to_object($value);
}
}
return $config;
}
}
echo config::get('people')->name; //dave
config::get('people')->name = 'bob';
echo config::get('people')->name; // should be bob, is dave
* name是什麼意思是硬編碼到類中?如果夠短,發佈'get'方法。 –