Creating the Singleton design pattern in PHP5

前端 未结 21 2072
猫巷女王i
猫巷女王i 2020-11-22 04:21

How would one create a Singleton class using PHP5 classes?

21条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 05:08

    This article covers topic quite extensively: http://www.phptherightway.com/pages/Design-Patterns.html#singleton

    Note the following:

    • The constructor __construct() is declared as protected to prevent creating a new instance outside of the class via the new operator.
    • The magic method __clone() is declared as private to prevent cloning of an instance of the class via the clone operator.
    • The magic method __wakeup() is declared as private to prevent unserializing of an instance of the class via the global function unserialize().
    • A new instance is created via late static binding in the static creation method getInstance() with the keyword static. This allows the subclassing of the class Singleton in the example.

提交回复
热议问题