V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
jacob
V2EX  ›  问与答

这段 php 代码中的一个静态方法的问题

  •  
  •   jacob · 2015-04-02 17:11:09 +08:00 · 1865 次点击
    这是一个创建于 3318 天前的主题,其中的信息可能已经有所发展或是发生改变。

    Singleton::getInstance 既没被继承,也没被调用,那么cache是如何得到 它的实例的呢?$this->_handle = new StdClass(); 按我理解就是创建了一个空的对象,具体实现也无法明白

    <?php
    class Singleton
    {
        private static $_instances = array();
    
        protected function __construct()
        {
        }
    
        final public function __clone()
        {
            trigger_error("clone method is not allowed.", E_USER_ERROR);
        }
    
        final public static function getInstance()
        {
            $c = get_called_class();
    
            if(!isset(self::$_instances[$c])) {
                self::$_instances[$c] = new $c;
            }
    
            return self::$_instances[$c];
        }
    }
    
    class Cache Extends Singleton
    {
        private $_handle = null;
    
        protected function __construct()
        {
            $this->_connect();
        }
    
        private function _connect()
        {
            $this->_handle = new StdClass();
        }
    
        public function getHandle()
        {
            return $this->_handle;
        }
    }
    
    5 条回复    2015-07-24 17:50:49 +08:00
    hahasong
        1
    hahasong  
       2015-04-02 21:53:43 +08:00
    Cache::getInstance()会把$_handle赋值给$_instances['Cache']
    都singleton了还继承干什么,写的shenmagui
    jacob
        2
    jacob  
    OP
       2015-04-03 12:16:15 +08:00
    @hahasong getInstance 是final的,怎么会继承呢,
    hahasong
        3
    hahasong  
       2015-04-03 13:35:42 +08:00
    @jacob final只是不能覆盖,怎么不能继承
    jacob
        4
    jacob  
    OP
       2015-04-03 16:43:19 +08:00
    @hahasong 那是我理解错误。sorry
    laoyuan
        5
    laoyuan  
       2015-07-24 17:50:49 +08:00
    @jacob LZ,请问怎么在V2发代码啊?我只会用gist。。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2240 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 21ms · UTC 09:13 · PVG 17:13 · LAX 02:13 · JFK 05:13
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.