Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton pattern in PHP 8.0 and private magic methods

I am using a singleton class in PHP according to the following pattern:

class MY_Singleton
{
    public static function instance()
    {
      static $instance = false;
      if( $instance === false )
      {
        // Late static binding (PHP 5.3+)
        $instance = new static();
      }

      return $instance;
    }

    /**
     * Make constructor private, so nobody can call "new Class".
     */
    private function __construct() {}

    /**
     * Make clone magic method private, so nobody can clone instance.
     */
    private function __clone() {}

    /**
     * Make sleep magic method private, so nobody can serialize instance.
     */
    private function __sleep() {}

    /**
     * Make wakeup magic method private, so nobody can unserialize instance.
     */
    private function __wakeup() {}

}

This used to work just fine under PHP 7.X.X. Now, under PHP 8.0 I am getting warnings such as:

Warning: The magic method My_Singleton::__wakeup() must have public visibility in [...]

Should I implement a singleton differently under PHP 8.0? Or should I just turn off these warnings? If so, how do I do this in a way that is backward compatible with PHP 7.X.X?

like image 424
cgogolin Avatar asked Feb 14 '26 05:02

cgogolin


1 Answers

A quote from the PHP manual:

WARNING All magic methods, with the exception of __construct(), __destruct(), and __clone(), must be declared as public, otherwise an E_WARNING is emitted. Prior to PHP 8.0.0, no diagnostic was emitted for the magic methods __sleep(), __wakeup(), __serialize(), __unserialize(), and __set_state().

Change these magic methods to public or remove them entirely if you do not use them. The only reason __construct makes sense as a private method is to prevent the possibility of multiple instances of your class, I guess the same could be said for __destruct, and __clone. For the other methods it simply makes no sense, and PHP 8 has finally implemented a warning.

like image 175
Dirk J. Faber Avatar answered Feb 16 '26 17:02

Dirk J. Faber