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

2015-04-02 17:11:09 +08:00
 jacob

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;
    }
}
1888 次点击
所在节点    问与答
5 条回复
hahasong
2015-04-02 21:53:43 +08:00
Cache::getInstance()会把$_handle赋值给$_instances['Cache']
都singleton了还继承干什么,写的shenmagui
jacob
2015-04-03 12:16:15 +08:00
@hahasong getInstance 是final的,怎么会继承呢,
hahasong
2015-04-03 13:35:42 +08:00
@jacob final只是不能覆盖,怎么不能继承
jacob
2015-04-03 16:43:19 +08:00
@hahasong 那是我理解错误。sorry
laoyuan
2015-07-24 17:50:49 +08:00
@jacob LZ,请问怎么在V2发代码啊?我只会用gist。。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/181159

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX