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
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If this is not your bug, you can add a comment by following this link.
If this is your bug, but you forgot your password, you can retrieve your password here.
Password:
Status:
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

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-2023 The PHP Group
All rights reserved.
Last updated: Sat Jan 28 15:03:49 2023 UTC