php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #78451 No possibility make Singleton in the PHP
Submitted: 2019-08-24 11:56 UTC Modified: 2019-08-24 16:53 UTC
From: forziforzi at gmail dot com Assigned:
Status: Not a bug Package: Class/Object related
PHP Version: 7.3.8 OS:
Private report: No CVE-ID: None
View Add Comment Developer Edit
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please !
Your email address:
MUST BE VALID
Solve the problem:
24 + 18 = ?
Subscribe to this entry?

 
 [2019-08-24 11:56 UTC] forziforzi at gmail dot com
Description:
------------
---
From manual page: https://php.net/class.closure
---

So, no Singleton in the PHP!

Test script:
---------------
<?php

final class A {
    private function __construct() {}
    private function __clone() {
        throw new \Exception('Singleton');
    }
    private function __sleep() {
        throw new \Exception('Singleton');
    }
    private function __wakeup() {
        throw new \Exception('Singleton');
    }
    public static function instantiate() {
        static $obj;
        return $obj = $obj ?? new self;
    }
}

$closure = function () {
    $class = get_class($this);
    return new $class;
};

$obj = A::instantiate();

var_dump($obj);
var_dump($closure->call($obj));



Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2019-08-24 16:53 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2019-08-24 16:53 UTC] requinix@php.net
PHP allows you to shoot yourself in the foot if you wish.
 [2019-08-25 19:00 UTC] jasny@php.net
If you really care, you can do this;

<?php

final class A {
    static $obj;

    private function __construct() {
        if (isset(self::$obj)) {
            throw new \Exception('Singleton');
        }
        self::$obj = $this;
    }
    private function __clone() {
        throw new \Exception('Singleton');
    }
    private function __sleep() {
        throw new \Exception('Singleton');
    }
    private function __wakeup() {
        throw new \Exception('Singleton');
    }
    public static function instantiate() {
        return self::$obj ?? new self;
    }
}
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Apr 19 23:01:28 2024 UTC