duanlei2458 2015-01-01 20:15
浏览 60
已采纳

PHP static关键字与new一起用于构建对象

I am reading about Patterns in OOP and came across this code for the singleton pattern:

class Singleton
{
    /**
     * @var Singleton reference to singleton instance
     */
    private static $instance;

    /**
     * gets the instance via lazy initialization (created on first usage)
     *
     * @return self
     */
    public static function getInstance()
    {

        if (null === static::$instance) {
            static::$instance = new static;
        }

        return static::$instance;
    }

    /**
     * is not allowed to call from outside: private!
     *
     */
    private function __construct()
    {

    }

    /**
     * prevent the instance from being cloned
     *
     * @return void
     */
    private function __clone()
    {

    }

    /**
     * prevent from being unserialized
     *
     * @return void
     */
    private function __wakeup()
    {

    }
}

The part in question is static::$instance = new static;. What exactly does new static do or how does this example work. I am familiar with your average new Object but not new static. Any references to php documentation would help greatly.

  • 写回答

1条回答 默认 最新

  • douchongbang6011 2015-01-01 20:22
    关注

    basically that is a extendable class, and whenever you call getInstance() you will get a singleton of the whatever class you call it in (that extends this singleton class). If you only use it in one instance, you could hardcode the classname, or use new self if you had hardcoded this in your class.

    Also, the singleton is regarded a anti-pattern, see the answer her for more details on this pattern why-is-singleton-considered-an-anti-pattern

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 arduino控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥85 maple软件,solve求反函数,出现rootof怎么办?
  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题