duanliang1999 2011-02-14 22:18
浏览 39
已采纳

创建单身人士 - 这是真的吗?

I am trying to create my own sort of lightweight,yet OOP way to keep track of loaded files and their appropriate versions (not yet implemented) in my PHP framework to be able to easily test dependency issues in the future.

Here's my current code, but being a total newcomer to OOP and patterns I am not able to determine if I have accomplished a proper Singleton or not:

class loadRegistry {

    private static $registry = null;

    private function __construct(){

        if (is_null(self::$registry));
        self::$registry = array();

    }

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

    public static function set($filename){

        if ( isSet( self::$registry[$filename]) AND !empty($filename) ) {
            throw new Exception("File already loaded");
        }
        else self::$registry[$filename] = '';
    }

}

loadRegistry::set('filename');
loadRegistry::set('filename2');

$reg = loadRegistry::get();
  • 写回答

4条回答 默认 最新

  • du27271 2011-02-14 22:25
    关注

    No, it is not a singleton. You are actually only playing with static properties. A singleton would be more like this:

    class Registry {
    
        private static $registry = null;
        private $data;
    
        private function __construct(){
            $this->data = array();
        }
    
        public static function getInstance() {
            if (is_null(self::$registry)) {
                self::$registry = new Registry();
            }
            return self::$registry;
        }
    
        public function set($filename){
            if (isset($this->data[$filename]) && !empty($filename) ) {
                throw new Exception("File already loaded");
            }
            else {
                $this->data[$filename] = '';
            }
        }
    
        // further **instance** methods
    }
    
    $reg = Registry::getInstance();
    $reg->set('filename');
    $reg->set('filename2');
    

    I don't know whether you can set the constructor as private in PHP... I think not.

    There is a difference between static classes$ and a singleton. A singleton allows to have only one instance at a time. For static classes, you don't even need an instance. In addition, static properties are shared between all instances of the class (in case you create an instance).

    You normally use static classes if you don't need an instance to hold some state.

    $: There are no real static classes. Only members can be defined as static. I'd say a class that has only static members can be called a static class.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度