简体   繁体   中英

PHP static class return reference

I have class with a static method. The static method returns a private static stdClass object.

myclass::get() // returns stdClass object
myclass::get()->name // name is hardcoded into the class

How would I change name's value like:

myclass::get()->name = 'bob';

and have it set?

I tried returning the object like:

return &self::$static_object;

But that throws syntax errors.

What can i do?

EDIT posted code for clarification

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

Returning by reference in the get() method should do the trick:

public static function &get() {
    return self::$static_object;
}

But, I think you should revisit your design, as this kind of coding is highly frowned upon and will cause maintenance and testability headaches down the road.

What you are doing and the answer from drrcknlsn break Encapsulation . That is bad.

The correct way to do this is to create a setter method.

public static function set($key, $value) {
  // set $config property...
}

You missed self in if (isset($configs[$config_name])) { . It should be

if (isset(self::$configs[$config_name])) {
  return self::$configs[$config_name];
}

Otherwise each time you call config::get('people') , you will be reading your config file which most likely returns an array and convert it to an object before returning it. Any changes you make to the object in self::$configs[$config_name] are overwritten by the newly created object.

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