Ozz*_*zzy 3 php static reference object
我有一个静态方法的类.static方法返回私有静态stdClass对象.
myclass::get() // returns stdClass object
myclass::get()->name // name is hardcoded into the class
Run Code Online (Sandbox Code Playgroud)
我如何更改名称的值,如:
myclass::get()->name = 'bob';
Run Code Online (Sandbox Code Playgroud)
并设置好吗?
我尝试返回对象,如:
return &self::$static_object;
Run Code Online (Sandbox Code Playgroud)
但这会引发语法错误.
我能做什么?
EDIT发布了代码以便澄清
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
Run Code Online (Sandbox Code Playgroud)
在get()方法中通过引用返回应该做的诀窍:
public static function &get() {
return self::$static_object;
}
Run Code Online (Sandbox Code Playgroud)
但是,我认为您应该重新审视您的设计,因为这种编码非常不受欢迎,并且会导致维护和可测试性问题.