Building a Singleton Trait with PHP 5.4

后端 未结 5 2031
温柔的废话
温柔的废话 2020-12-14 02:22

We recently had a discussion if it was possible to build a trait Singleton PHP Traits and we played around with it a possible Implementation but ran into issues

5条回答
  •  时光取名叫无心
    2020-12-14 02:51

    Quick solution we've found (thanks chat!):

    If a trait and a class both define the same method, the one of class if used

    So the Singleton trait only works if the class that uses it doesn't define a __construct()

    Trait:

    init();
        }
        protected function init() {}
        final private function __wakeup() {}
        final private function __clone() {}    
    }
    

    Example for a consuming class:

    foo = 1;
            echo "Hi!\n";
        }
    }
    
    var_dump(A::getInstance());
    
    new A();
    

    The var_dump now produces the expected output:

    Hi!
    object(A)#1 (1) {
      ["foo"]=>
      int(1)
    }
    

    and the new fails:

    Fatal error: Call to private A::__construct() from invalid context in ...
    

    Demo

提交回复
热议问题