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 Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
If you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: forziforzi at gmail dot com
New email:
PHP Version: OS:

 

 [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

Pull Requests

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: Mon Dec 09 13:01:26 2024 UTC